cin >> number;
cout << "Not a number " << endl;
cout << "number is " << number << endl;
I'm not really sure what I want to ask here. So if I run this program it will repeat cin >> number until I enter a non-int. But then it prints the last int value I gave it. Does it not overwrite the value of number if it isn't the correct type?
Well how about if I do this (Take away the ! in line 11).
So then it should repeat until it gets an int. But...it goes into an infinite loop of displaying "Not a number". How come it doesn't do line 8 cin >> number; ? I also tried putting a cin >> number outside of the loop and it still just skips over it.
And the example where I seen this used it like this.
1 2 3 4 5 6 7
cin >> Item;
while (! cin.fail())
cin >> Item;
I see that this works, but what if I don't want it to stop once I enter something that isn't the right type?
cin.fail() detects whether the value entered fits the value defined in the variable.
But if cin.fail() is true, it means that
a) the entered value does not fit the variable
b) the varialbe will not be affected
c) the instream is still broken
d) the entered value is still in the buffer and will be used for the next "cin >> variable"statement.
Hence you have to do the following:
a) repair the instream via cin.clear();
b) clear the buffer with cin.ignore(std::numeric_limits<int>::max(),'\n');
In your exampe, you have the result that, after entering the wrong value, your stream is broken. But you do not repair the stream and you do not clear the buffer. So, no matter how often the loop will be made, "cin >> number" will always retrieve the FIRST value you have entered after starting the programm. And thus, it will always return a cin.fail() and your loop can not be left by any value you will enter afterwards.