无法时间输入:C++

Can't time input: C++

我正在尝试制作一个游戏来测试我的 C++ 技能,在游戏中我创建了一个 class 名为 Player 的方法函数定义 attack()。它根据 Player 方法变量打印一个随机字符串,然后要求玩家在尽可能短的时间内输入该字符串:

//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";
}

不行,我到处找答案。它只是 returns 没有意义的随机数。当我看到人们使用 difftime() 函数时,他们总是将 tm 结构转换为 time_t 变量,然后将其作为第二个参数。你需要用这个吗? difftime() 函数 return 是什么类型的数据?我究竟做错了什么?是编译器吗?非常感谢您的帮助。

只需将时间测量值放在 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";