Does not read 0

Hello! The program doesn't seem to like setting the input variable to 0. With any other number, the the program displays the number inputted before and after checking for a failed input, however with 0, it'll show it before and show that the variable input is blank afterwards. Any idea as to why?

1
2
3
4
5
6
7
8
9
10
11
12
             cin >> input; // Allows user input
cout << "input" << input << endl;
            if (cin.fail()) // Checks for valid input
            {
            cout << "Illegal value. Try again ";
            cin.clear();
            cin.ignore (1000,'\n');
            }
        } while (input == cin.fail());  // Repeats while input is invalid

cout << "input after fail check" << input << endl;
    // Repeat while input is invalid 
cin.fail() returns a boolean (true or false) value. In numeric terms, it translates to false == 0 and true == 1.

Hence when the valid integer 0 is entered, the cin fail flag is false.
The condition while (input == cin.fail()); will thus evaluate as true, because (0 == 0) is true.

Try something like this instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    int input = 0;
    
    cout << "Please enter an integer: ";
    
    while (!(cin >> input))
    {
        cout << "input " << input << endl;
    
        cout << "Illegal value. Try again \n";
        cin.clear();
        cin.ignore (1000,'\n');
        cout << "Please enter an integer: ";
    }  
        
    cout << "input after fail check " << input << endl;


the line
 
    while (!(cin >> input))

first allows the user to enter a value, then checks the state of cin.
if (!cin ) is effectively the same as if (cin.fail())

http://www.cplusplus.com/reference/ios/ios/fail/
http://www.cplusplus.com/reference/ios/ios/operator_not/

Last edited on
Thank you! I tried that, however, and got the same results as before
I tried that, however, and got the same results as before

Well, I tested the code before posting.
Please enter an integer: abc
input 0
Illegal value. Try again
Please enter an integer: 0
input after fail check 0


Please enter an integer: x
input 0
Illegal value. Try again
Please enter an integer: 765
input after fail check 765


Perhaps you missed something (maybe did not compile the code perhaps) ?
OP: if you're trying to make some variant of your program work instead of using Chervil's then remove the while(...) (line 9) and use an else instead for the reason s/he mentions:
1
2
3
4
5
6
7
8
9
10
11
if (cin.fail()) // Checks for valid input
{
	cout << "Illegal value. Try again ";
        cin.clear();
        cin.ignore (1000,'\n');
}
//while (input == cin.fail());  // Repeats while input is invalid
else
{
       cout << "Input was indeed " << input << '\n';
}
Topic archived. No new replies allowed.