2016-11-10 73 views
0

我想製作一個遊戲來測試我的C++技能,並且在遊戲中我使用方法函數定義attack()創建了一個名爲Player的類。它打印出基於玩家方法變量一個隨機字符串,然後它要求玩家輸入儘可能少的時間字符串可能:不能輸入時間:C++

//definitions for Player 
int Player::attack() 
{ 
    std::cout << "You are now attacking. \n"; 
    std::cout << "You must enter this string in as little time as possible:"; 

    std::string r = randStr(wordc); 
    std::cout << r << "\n"; 

    std::string attack; 
    double seconds_since_start; 
    time_t start = time(0); 
    while (true) 
    { 
      std::cin >> attack; 
      if (attack == r) {break;} 
      seconds_since_start = difftime(time(0), start); 
    } 
    std::cout << "You typed the word in " << seconds_since_start << "seconds\n"; 
} 

它不工作,我已經到處找一個答案。它只是返回無意義的隨機數字。當我看到有人使用difftime()函數時,他們總是將tm結構轉換爲time_t變量,然後將其作爲第二個參數。你需要使用這個嗎? difftime()函數返回什麼類型的數據?我究竟做錯了什麼?它是編譯器嗎?我非常感謝你的幫助。

+1

你可以找到'difftime一些文檔()'[這裏](http://en.cppreference.com/w/cpp/chrono/c/difftime)。但對於C++,您應該更喜歡['chrono'](http://en.cppreference.com/w/cpp/header/chrono)。 – wally

+0

可能您應該嘗試使用[參考文檔](http://en.cppreference.com/w/c/chrono/difftime)中給出的示例。 –

+6

如果用戶在第一次嘗試時輸入了正確的字符串,則不用設置'seconds_since_start'即可跳出循環。即使用戶不這樣做,您仍然不會將最後的成功嘗試納入測量。將'seconds_since_start'賦值移至循環後面的點。 –

回答

0

只需在break;之前在if區塊中放置時間測量值,延遲就可以正確計算。但是,在下次嘗試attack != r時,必須重新啓動計數器(如果需要)。

double seconds_since_start; 
time_t start = time(0); 
while (true) 
{ 
    std::cin >> attack; 
    if (attack == r) { 
     // stop the counter and measure the delay 
     seconds_since_start = difftime(time(0), start); 
     break; 
    } 
    // restart the counter (if needed) 
    start = time(0); 
} 
std::cout << "You typed the word in " << seconds_since_start << "seconds\n"; 
+0

非常感謝你!這只是一個簡單的邏輯錯誤,我錯過了! – Chopdops