Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SIGINT handling and getline

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?

like image 626
ThP Avatar asked Dec 29 '25 02:12

ThP


1 Answers

Try adding the following immediately before your cout statement:

cin.clear();  // Clear flags
cin.ignore(); // Ignore next input (= Ctr+C)
like image 163
Konrad Rudolph Avatar answered Dec 31 '25 19:12

Konrad Rudolph