@Almi
Your first attempt wasn't bad at all, it does what's asked for.
The confusing behaviour is actually simple:
If you enter ".4" it you will end up in the cin.fail() branch, because .4 is not an integer. Actually you could use a more compact notaion, I'll give an example later.
If you had entered "4 4" (that is 4 space 4) at the input, your loop would have run twice, each time retrieving the integer 4 from cin.
When you entered "4.4" it also goes through the loop twice. The first time it retrieves 4 from cin, and the second time it tries ".4" and fails
You may not have realised this, maybe you were thinking it's waiting for you type another number and hit enter before continuing, but in actual fact, it doesn't (since you're dealing with int, it cannot), get "4.4" as a single input.
So for the first "4" you get the "Yes an integer" and for the "." you get the "Whoops not an integer!"
You sent your prompt to cout (which is buffered) and the error to cerr (which is not buffered) so you have 2 different iostreams being multiplexed onto your screen, that's why the text is mixed.
You would have seen the same behaviour if you entered something like "4y"
I promised an example alternative to the 2 stage cin >> and cin.fail():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int input = 0;
cout << "Enter an integer" << endl;
while(cin >> input)
{
cout << "Yes an integer" << endl;
cout << "Enter an integer" << endl;
}
cout << "Whoops not an integer!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
|