所以我需要为一个程序编写一个 whileloop 来提示用户:
char vector[10];
while(????){
print("Write a number");
scanf("%s",vector);
}
printf("Goodbye");
当用户按 ctrl+c 时,程序应该打印出再见并关闭。 我很确定在这种情况下我不能使用 putchar?
最佳答案
#include <windows.h>
#include <stdio.h>
static end_flag = 0;
BOOL WINAPI controlHandler(DWORD type){
if(type == CTRL_C_EVENT){
end_flag = 1;
return TRUE;
}
return FALSE;
}
int main(){
char vector[10];
if (!SetConsoleCtrlHandler(controlHandler, TRUE)) {
fprintf(stderr, "Failed SetConsoleCtrlHandler");
return -1;
}
while(!end_flag){
printf("Write a number ");
scanf("%s",vector);
}
printf("Goodbye");
return 0;
}
<小时/>
CTRL+Z版本
#include <stdio.h>
int main(){
char vector[10];
while(1){
printf("Write a number ");
if(scanf("%s", vector)==EOF)//press CTRL+Z
break;
}
printf("Goodbye");
return 0;
}
关于c - 如何在 Windows 上用 c 中的 ctrl+c 结束 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816352/