gpt4 book ai didi

C++ 时间限制不起作用

转载 作者:行者123 更新时间:2023-11-28 05:26:54 25 4
gpt4 key购买 nike

如果用户在几秒钟内没有输入,我有这个程序应该结束并打印一条消息。但是现在时间限制似乎不起作用,尽管我的代码看起来合乎逻辑。 (如果用户没有输入任何内容,时间不会消失)这是为什么?

int userInput = 0;
int now = time(0);
int later = 0;
int elapsed = 0;
do {
later = time(0);
elapsed = later - now;
cout << "Enter number" <<endl;
cin >> userInput;
switch (userInput)
{
case 1:
elapsed = 0;
break;
}

} while (elapsed < 4 && !_kbhit());


if (elapsed == 4)
{
system("cls");
cout << "Too Slow!! Now You're on the Menu!";
return 0;
}

最佳答案

不提供保证,但如果使用 kbhit 是解决方案的一部分,那么您可能只想在检测到某些键盘事件时尝试阅读。

int userInput = 0;
int now = time(0);
int later = 0;
int elapsed = 0;

cout << "Enter number" <<endl;

do {
later = time(0);
elapsed = later - now;
if(_kbhit()) { // we **may** have some input
cin >> userInput;
// this is useless for timing purposes!!
// A simple `break` should suffice.
switch(userInput)
{
case 1:
elapsed = 0;
break;
}
}

} while (elapsed < 4);


if (elapsed == 4)
{
system("cls");
cout << "Too Slow!! Now You're on the Menu!";
return 0;
}

关于C++ 时间限制不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com