[英]catch ctrl-c in c++ cause ignore scanf
I'm trying to catch Ctrl + c . 我试图赶上Ctrl + c 。 I search on google and find this code:
我在Google上搜索并找到以下代码:
#include <windows.h>
#include <iostream>
#include <signal.h>
#include<cstdio> using namespace std;
BOOL WINAPI ConsoleHandler(DWORD CEvent){
if(CEvent == CTRL_C_EVENT){
cout<<"ctrl c pressed"<<endl;
Sleep(100);
}
return TRUE; }
int main(int argc, char *argv[]){
char a[10];
if (SetConsoleCtrlHandler( (PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE){
cout<<"Unable to install handler!";
return -1;
}
while(true){
fflush(stdin);
scanf("%[^\n]s",a);
cout<<a<<endl;
} }
when run this code i input " abcd " then it display " abcd " normaly and then i press Ctrl + c ' it display ctrl c pressed abcd**" how can i fix this code so that it just display " ctrl c pressed " when i press Ctrl + c ? 当运行此代码I输入“ABCD”,那么它显示“ABCD” normaly,然后我按下Ctrl + C'它显示CTRL下加压ABCD **”如何解决这个代码,以便它只是显示‘CTRL下加压 ’时我按Ctrl + c键 ?
The reason it is outputting "abcd" again is because it is still in your a
variable from last time. 再次输出“ abcd”的原因是因为它自上次仍在您
a
变量中。 The best way to fix it is to use the return value of scanf
. 解决该问题的最佳方法是使用
scanf
的返回值。 scanf
returns the number of items filled in, so in your case you want it to return 1. scanf
返回已填写的项目数,因此,在您的情况下,您希望它返回1。
if (scanf("%[^\n]s", a) == 1)
cout<<a<<endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.