[英]How to end a whileloop with ctrl+c in c on windows?
So i need to write an whileloop for a program that's supposed to prompt the user with this: 所以我需要为一个程序编写一个whileloop,以提示用户:
char vector[10];
while(????){
print("Write a number");
scanf("%s",vector);
}
printf("Goodbye");
The program is supposed to print goodbye and close when the user presses ctrl+c. 该程序应该在用户按下ctrl + c时打印再见并关闭。 Im pretty sure I cant use putchar in this case?
我很确定在这种情况下不能使用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 version 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;
}
see https://superuser.com/questions/214239/whats-the-command-prompts-equivalent-to-cygwins-ctrlz : 参见https://superuser.com/questions/214239/whats-the-command-prompts-equivalent-to-cygwins-ctrlz :
Depends on what you mean by "quit something";
取决于您所说的“放弃某物”; within Windows cmd:
在Windows cmd中:
Ctrl+Z sends the EOF character, which could terminate a process if you're providing input, but otherwise will probably do nothing.
Ctrl + Z发送EOF字符,如果您要提供输入,则该字符可能会终止进程,但否则可能无济于事。
Ctrl+C normally sends SIGINT to the foreground process, which should terminate it, but programs can respond however they like - ie, they can catch the signal but then ignore it.
Ctrl + C通常将SIGINT发送到前台进程,该进程应终止它,但程序可以根据自己的喜好进行响应-即,他们可以捕获信号,然后忽略它。 The command can also be remapped to other jobs (such that for a specific program it doesn't really send a signal) or ignored entirely.
该命令还可以重新映射到其他作业(例如,对于特定程序,它实际上并不发送信号)或完全忽略。
Ctrl+Break always sends SIGBREAK, which again should terminate the process, but unlike Ctrl+C cannot be remapped, but can still be ignored.
Ctrl + Break总是发送SIGBREAK,它再次应终止进程,但与Ctrl + C不同的是,它不能重新映射,但仍然可以忽略。 This is probably what you need.
这可能就是您所需要的。
I think this might be what you're looking for: 我认为这可能是您要寻找的:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683242%28v=vs.85%29.aspx http://msdn.microsoft.com/en-us/library/windows/desktop/ms683242%28v=vs.85%29.aspx
Post similar to this one on Stack Overflow: Catch Ctrl-C in C 在Stack Overflow上发布与此类似的文章: 在C中捕获Ctrl-C
You might want to check it out. 您可能需要检查一下。 Cheers!
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.