我正在制作一个测验程序。所以我想要的是,每当用户提出任何问题时,他都有 30 秒的时间来回答。在这 30 秒内,我希望每隔 1 秒发出一次嘟嘟声('\a')。现在我想要的是,一旦用户输入任何输入,这种蜂鸣声就应该停止。我创建了这个小函数来产生 30 秒的蜂鸣声void beep(){ for(int i=0;i<30;i++){cout<<"\a"; Sleep(1000); }
}
但我不知道如何在用户输入他/她的答案后立即停止它,因为一旦我调用它,在结束之前什么也做不了。
谁能给出任何解决方法吗?
免责声明:我不是 Windows 程序员,我不知道这是否是好的风格,或者是否可以编译或工作。我这里无法测试。然而,由于没有其他人给出解决方案,因此这是一个起点。当我了解更多信息时,我将编辑这个答案,并希望对此有更多了解的人会出现。
Edit: 我是假装的_kbhit()
到一个简单的函数返回false
,它至少可以编译并且看起来运行正常
Edit:好吧,我工作中确实有 MS Visual Studio,但我只是从不使用它。现在的代码可以编译并运行(但我怀疑时间已经关闭)。
Edit:更新为立即读回按下的键(而不是等待用户按下 Enter 键)。
这是重要的功能:http://msdn.microsoft.com/en-us/library/58w7c94c%28v=vs.80%29.aspx http://msdn.microsoft.com/en-us/library/58w7c94c%28v=vs.80%29.aspx
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <iostream>
#include <string>
int main()
{
time_t startTime, lastBeep, curTime;
time(&startTime);
lastBeep = curTime = startTime;
char input = '\0';
while ( difftime(curTime,startTime) < 30.0 )
{
if ( _kbhit() ) // If there is input, get it and stop.
{
input = _getch();
break;
}
time(&curTime);
if ( difftime(curTime,lastBeep) > 1.0 ) // More than a second since last beep?
{
std::cout << "\a" << "second\n" << std::flush;
lastBeep = curTime; // Set last beep to now.
}
}
if ( input )
{
std::cout << "You hit: \"" << input << "\"\n" << std::flush;
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)