SIGINT and getline processing

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 press ctrl-c while the program is waiting for input, I get the following output:
Enter text: received SIGINT

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

(the program continues the cycle without waiting for input)

What should I do?

+3
source share
1 answer

Try adding the following immediately before the statement cout:

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

Source: https://habr.com/ru/post/1723539/


All Articles