我正在尝试制作一款游戏来测试我的C ++技能,并且在游戏中我使用方法函数定义攻击()创建了一个名为Player的类。它根据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";
}
它没有用,我到处寻找答案。它只返回没有意义的随机数。当我看到人们使用difftime()函数时,他们总是将tm结构转换为time_t变量,然后将其作为第二个参数。你需要用这个吗? difftime()函数返回什么类型的数据?我究竟做错了什么?是编译器吗?我非常感谢你的帮助。
答案 0 :(得分:0)
只需将时间测量放在if
之前的break;
块中,就可以正确计算延迟。但是,对于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";