SIGINT handling and getline

て烟熏妆下的殇ゞ 提交于 2019-12-01 07:14:10

问题


I wrote this simple program:

void sig_ha(int signum)
{
cout<<"received SIGINT\n";
}

int main()
{
 string name;
 struct sigaction newact, old;
 newact.sa_handler = sig_ha;
 sigemptyset(&newact.sa_mask);
 newact.sa_flags = 0;
 sigaction(SIGINT,&newact,&old);

 for (int i=0;i<5;i++)
     {
     cout<<"Enter text: ";
     getline(cin,name);
     if (name!="")
         cout<<"Text entered: "<<name;
     cout<<endl;
     }
 return 0;
}

If I hit ctrl-c while the program waits for input I get the following output:
Enter text: received SIGINT

Enter text:
Enter text:
Enter text:
Enter text:

(the program continues the loop without waiting for input)

What should I do?


回答1:


Try adding the following immediately before your cout statement:

cin.clear();  // Clear flags
cin.ignore(); // Ignore next input (= Ctr+C)


来源:https://stackoverflow.com/questions/1775216/sigint-handling-and-getline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!