I am a beginner programmer learning c++. I am having a nagging issue with the cin command.
In the program section below, if I enter a wrong type at the 1st cin command, the program will not execute any of the following cin commands at all, but will execute the rest of the program.
//start
#include <iostream>
using namespace std;
int main()
{
int x=0;
cout << endl << "Enter an integer" << endl;
//enter integer here. If wrong type is entered, goes to else
if (cin >> x){
cout << "The value is " << x << endl;
}
else {
cout << "You made a mistake" << endl; //executes
cin.ignore();
cin.clear();
}
cout << "Check 1" << endl; //executes
cin >> x; //skips
cout << "Check 2" << endl; //executes
cin >> x; //skips
return 0;
}
//end
Instead of the if else, if i put the same concept in a loop
while (!(cin >> x))
the program goes into an infinite loop upon enterring a wrong input.
Please help me explain this phenomenon, as the text book i am following says the code typed above should work as intended.
Thank you
cinis an input stream. If an error occurscingoes into a let’s call it “error occured” state. While in this state no character input can be made, your request to collect a character from the input stream will be ignored. Withclear()you clear the error and the input stream stops ignoring you.Here is the ignore function prototype
This function gets characters from the input stream and discards them, but you can’t get any character if your stream is ignoring you, so you have to first
clear()the stream thenignore()it.Also, a note on the side: If someone inputs, for example
"abc", on the first input request yourcingets only one character that is'a'and"bc"stays in the buffer waiting to be picked up, but the next call tocingets the'b'and'c'stays in the buffer, so you again end up with an error.The problem with this example is that the
cin.ignore()if no arguments are handed to it only ignores 1 character after youclear(). and the secondcingets'c'so you still have a problem.A general solution to this problem would be to call
The first number just has to be some huge number that you don’t expect someone would enter, I usually put in 10000.
This call makes sure that you pick up all the characters from the false input or that you pick up every character before the enter was pressed so your input stream doesn’t get into the “error occurred” state twice.