first off i'd know using getline better alternative, however, curious why code doesn't work intended: , can't figure out why
#include <iostream> #include <string> using namespace std; int main() { while(1) { int input; cout << "---> "; cin >> input; if(cin.fail()) { char rd = cin.get(); cout << "failure" << rd << "=" << cin.fail() << " " << endl; } } return 0; }
intended: if integer entered, continue otherwise cin fails, pull 1 char stdin , output it. keep looping.
the way see it, cin.get() should clear bad input; never does: gets stuck in infintie loop. what?
cin.fail() detects whether value entered fits value defined in variable. if cin.fail() true, means
a) entered value not fit variable
b) varialbe not affected
c) instream still broken
d) entered value still in buffer , used next "cin >> variable"statement.
hence have following:
a) repair instream via cin.clear();
b) clear buffer cin.ignore(std::numeric_limits::max(),'\n');
#include <iostream> #include <string> using namespace std; int main() { while(1) { int input; cout << "---> "; cin >> input; if(cin.fail()) { char rd = cin.get(); cout << "failure" << rd << "=" << cin.fail() << " " << endl; cin.clear(); cin.ignore(); } } return 0; }
Comments
Post a Comment