我正在编写一个乘法表程序来帮助我的侄女学习。我希望她能够有一定的时间来回答每个问题(因此 for 循环起到了延迟的作用)。延迟起作用了,因为在延迟秒后程序输出“时间到了”!但是,程序仍然等待我输入一个值并按 Enter 键,然后才会评估答案并检查它是“正确”还是“错误”(这不能通过放置 printf 和 scanf 来解决)在 for 循环之后一起在循环内)。我知道延迟只是等待几秒钟,然后正常继续,这就是为什么我需要输入一个数字并按 Enter 键。但是,我不知道如何解决这个问题。
基本上,如果延迟秒过去并且她没有输入值,我希望程序自动“输入”,从而导致答案“错误”。但是,如果她在延迟秒结束之前输入一个值并按 Enter 键,我仍然想检查它是“正确”还是“错误”。我已经寻找了其他方法来做到这一点,但我就是找不到正确的方法。这是到目前为止的代码(同样,我知道 for 循环延迟只会让程序在正常继续之前等待延迟秒,但我不知道如何解决这个问题。
time_t start_time = 0;
int delay = 0;
int answer = 0;
int correct = 0;
int wrong = 0;
printf("How long should the delay be?:\t");
scanf("%d", &delay);
start_time = clock();
printf("\n2 x 4 =\t");
for( ;clock() - start_time <= delay*CLOCKS_PER_SEC; );
printf("\n\nTime's up!\n\n");
scanf("%d", &answer);
if(answer == 8)
{
printf("\nCorrect!\n");
++correct;
}
else if(answer != 8)
{
printf("\n\aWrong!\n");
++wrong;
}
编辑:我正在运行 Windows 并使用 CodeBlocks 和 mingw32。我只希望该程序是一个简单的 .exe 文件,它将通过 CMD 运行。 (不过它已经做到了)。
最佳答案
您的目标无法通过 scanf()
实现,因为它是一个阻塞调用 - 在用户输入输入之前,不会执行下一个代码行。这不是你想要的。
您可以使用另一个库函数kbhit()
- 如果按下任何键,它会返回 > 0。但它不会告诉你按下了哪个键。为此,您必须调用getch()
。
kbhit是 conio.h 的一部分
所以你的代码是:
bool bAnswered = false;
for( ;clock() - start_time <= delay*CLOCKS_PER_SEC; )
{
if(kbhit() > 0) //Some key is pressed
{
answer = getch(); //Read that key
bAnswered = true; // User has answered
}
}
// Print message if there wasn't any key press.
if(bAnswered == false)
{
printf("\n\nTime's up!\n\n");
}
if(answer == 8)
{
printf("\nCorrect!\n");
++correct;
}
else if(answer != 8)
{
printf("\n\aWrong!\n");
++wrong;
}
上述代码的问题是您一次只能读取 1 个字符。我将其留给您实现。
另外,您需要编写额外的代码将 ASCII 转换为整数,因为 getch()
返回 ASCII 字符。
关于c - 用C语言的定时器读取一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593588/