0
{
    int val;
    string str;
    cin >> val;    
    cin >> str;
}

When I write C++ program, I met a problem. I define a int variable "val", and I write this: cin >> val, but I input is 'g'. When I write next statement cin >> str; the cin directly use the 'g' again, but this is not my want.

I want clear the cin buffer so that I can input the correct number to str.

I have find a solution to this problem. Here is the solution

{
    int val;
    string str;
    cin >> val;    
    cin >> str;
}

Now I want know that if exist a more better way and How to clear current buffer on Linux

Thanks!!!

ken
  • 1
  • 1

1 Answers1

1
cin>>val;    
cin.clear();
cin.sync();
// ...
William Chan
  • 267
  • 2
  • 12