Basically, your cin thread is in a cin state and thus returns immediately when you try to read it. Rewrite your example as follows:
#include <iostream> int main() { signed char sch = 0; int n = 0; while(std::cin >> n){ sch = n; std::cout << n << " --> " << sch << std::endl; } }
cin >> n will return a link to cin , which you can check for "quality factor" in a conditional expression. So basically " while(std::cin >> n) " basically says "while I could still read standard input, do the following"
EDIT: the reason it re-displays the last good entered value is because it is the last value successfully read in n, reading failures will not change the value of n
EDIT: as noted in the comment, you can clear the error state and try again, something like this will probably work and just ignore the bad numbers:
#include <iostream> #include <climits> int main() { signed char sch = 0; int n = 0; while(true) { if(std::cin >> n) { sch = n; std::cout << n << " --> " << sch << std::endl; } else { std::cin.clear(); // clear error state std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it } } }
Evan teran
source share