我是 C 语言的初学者。我在 Windows 上的 Code::Blocks 中编写了一个 C 程序,它将接受 int
输入并在下一行打印它。我想运行循环直到按转义键,但我不能这样做。我的代码是:
#include <stdio.h>
#include <conio.h>
int main(void)
{
int k;
do {
scanf("%d",&k);
printf("%d\n", k); // print value
} while (k != 27); // end when Esc pressed
return 0;
}
循环正在运行。我输入一个整数,它会在下一行打印它。但按退出键并不会终止它。当我按 Esc 键时什么也没有。我想运行该程序,直到按下转义键,同时仍然接受用户的 int
类型输入。如何在按转义键时终止程序?
最佳答案
查看函数 kbhit();
和 getch();
一个可能的解决方案是:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(){
char ch;
int k;
while (1) {
if (kbhit) {
scanf("%d",&k);
printf("%d\n", k);
// Stores the pressed key in ch
ch = getch();
// Terminates the loop
// when escape is pressed
if (int(ch) == 27)
break;
}
}
关于C 程序在按 escape 时终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51384597/