In my program, I define a variable of type int, and use cin to input integer into this variable. When my input is like '123' or '123adfd', it works perfectly. But when I input something like 'abc', infinite loop occurs. I know that this infinite loop has something to do with the input buffer. But I just don't know how to clear the input buffer. I had tried many methods but all in vain. I need your help badly. Thanks in advance.
Here is my code:
Code:#include <iostream> #include <limits> using namespace std; int main() { int var; while ( 1 ) { cout << "Please input an integer." << endl; cin >> var; cin.ignore(numeric_limits<streamsize>::max(), '\n'); /* * I also tried "while ((ch = cin.get()) != '\n' && ch != EOF);" and "cin.sync()", * but they did no help. * */ } return 0; } /* When inputing something like 'abc', it prints "Please input an integer." infinitely. * * Please input an integer. * abc * Please input an integer. * Please input an integer. * Please input an integer. * Please input an integer. * Please input an integer. * Please input an integer. * Please input an integer. * ... ... ... * */