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())
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';
}