Sorry for the noobish question here, but I am just learning C++ and I am looking for the standard way of dealing with this problem. I am using VS2005.
Given a program:
#include <iostream>
using namespace std;
int main( )
{
while ( true )
{
cout << "enter anything but an integer and watch me loop." << endl;
int i;
cin >> i;
}
return 0;
}
If you enter anything but an integer the program will never allow you to enter anything again. Now, I realize that this is because there is input left on the stream after the format fails, so each call to cin << i just reads up to the next end line (I think). How do you guys clear out the stream or deal with this problem? It must be pretty common.
surround the cin call with an if.
The cin will return false if wrong data is read.
so:
if (!cin >> i) {
cin.clear();
cin.ignore(INT_MAX, '\n');
cout << "Haha, your looping efforts have been thwarted dear sir\n";
}
cin.flush() should do the trick (according to cppreference.com) but not on VS apparently.
cin.clear() resets all flags to a good state.
cin.ignore with a large number and until '\n' should work.
Alright, I found the answer. The answer is...
Don't do this. Do not mix formatted and unformatted input using operator >>. Here is a good article on the subject:
http://www.cplusplus.com/forum/articles/6046/
Basically, the code changes to:
#include <iostream>
#include <string>
#include <stream>
using namespace std;
int main( )
{
while ( true )
{
cout << "enter anything but an integer and watch me loop." << endl;
string input;
getline( cin, input );
int i;
stringstream stream( input );
if ( stream >> i ) break;
}
return 0;
}
cin.ignore(int num_bytes_to_ignore); will do it.
You can also use stdio, fflush(fd); where fd is one of stdout,stderr,stdin.