Muffi
Muffi

Reputation: 55

cin condition checking error

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

Upvotes: 3

Views: 13817

Answers (2)

CodeJunkie
CodeJunkie

Reputation: 147

cin is an input stream. If an error occurs cin goes 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. With clear() you clear the error and the input stream stops ignoring you.

Here is the ignore function prototype

istream&  ignore ( streamsize n = 1, int delim = EOF );

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 then ignore() it.

Also, a note on the side: If someone inputs, for example "abc", on the first input request your cin gets only one character that is 'a' and "bc" stays in the buffer waiting to be picked up, but the next call to cin gets 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 you clear(). and the second cin gets 'c' so you still have a problem.

A general solution to this problem would be to call

cin.ignore(10000, '\n');

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.

Upvotes: 3

Mike
Mike

Reputation: 1

You may also want to try if ( std::cin.fail() )

as a backup to prevent a crash due to input of the wrong type when prompted

Upvotes: 0

Related Questions