我想製作一個遊戲來測試我的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()函數返回什麼類型的數據?我究竟做錯了什麼?它是編譯器嗎?我非常感謝你的幫助。
你可以找到'difftime一些文檔()'[這裏](http://en.cppreference.com/w/cpp/chrono/c/difftime)。但對於C++,您應該更喜歡['chrono'](http://en.cppreference.com/w/cpp/header/chrono)。 – wally
可能您應該嘗試使用[參考文檔](http://en.cppreference.com/w/c/chrono/difftime)中給出的示例。 –
如果用戶在第一次嘗試時輸入了正確的字符串,則不用設置'seconds_since_start'即可跳出循環。即使用戶不這樣做,您仍然不會將最後的成功嘗試納入測量。將'seconds_since_start'賦值移至循環後面的點。 –