Your loop should be checking the state of cin
after reading from it. If the failbit is set, the input operation failed. You could re-prompt after that.
E.g., if (!cin) { ... }
Question
I noticed while I was implementing a simple linked-list stack that cin
doesn't re-prompt if I enter a value larger than the max. size of an integer. For example:
int input;
do {
cin >> input;
if (input == -1)
break;
else if (input == 0)
pop();
else
push(input);
} while (input != -1);
would loop forever if I entered a number which exceeds the size of an int
(note that the type of input
is int
).
This is likely the most dangerous behaviour that I have encountered so far of a relatively well isolated C++ program in the short time that I have been programming in this language. Because the loop pushed the input on every iteration, my program's memory usage sharply increased to over 1GB in less than 30 seconds... my computer nearly crashed.
So I'm wondering: why would cin
exhibit this behaviour?
P.S. I resolved this infinite-loop problem by adding input = -1
before reading the input. Is this the best way to prevent the looping?
Solution
Your loop should be checking the state of cin
after reading from it. If the failbit is set, the input operation failed. You could re-prompt after that.
E.g., if (!cin) { ... }
OTHER TIPS
I would consider re-writing like this:
int input;
while(!(std::cin >> input)) {
cout << "you entered in the wrong type, please try again" << endl;
cin.clear();// clear error flags from cin
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //extracts characters from the stream and discards them until a newline is found
}
if(input == 0){
pop();
}else{
push(input);
}
Note that entering in a value that's larger than the maximum allowed int
will cause the fail bit for cin
to be set. This solution relies on this behaviour to work.
Signed integer types just wrap around if you exceed their maximum value.
To counteract it you should only push the input to the stack if it is within the acceptable bounds