This loop is supposed to get the number of players for a tic tac toe game I'm trying to wright. My problem comes in the else statement when the value of the variable players is anything that's not a number. for example if i enter x instead of a number. when run the output in the else statement just repeats forever in the console.
I'm not sure whats wrong with it. I just started the other day with a C++ book and cant figure it out with that. Also did not find anything on Google.
the code is as follows:
do {
cin >> players;
if (players == 1 || players == 2 || players == 0){
good_value = true;
}
else{
cout << "\n\n invalid number please reenter the number of players ";
good_value = false;
}
Entering a non-number into the input stream corrupts it.
This causes your cin >> players; line to be skiped!
1 2 3 4 5 6 7 8 9 10 11 12 13 14
do {
cin >> players;
if( !cin.good() ) { //make sure the stream is not corrupted
cerr << "Whoops! That's not an integer.\n"; //send a message to the standard error stream (another output stream)
return 1; //exit the program with an error code
}
good_value = players >= 0 && players <= 2; //easier to read, and works in a more general case
if( !good_value )
cout << "invalid number please reenter the number of players\n";
} while( !good_value ); //not good_value, is a bit more readable then good_value == false
at least I know I'm not going crazy with confusion now :). well if that's the case how might I make it run the actions in the else statement if someone accidentally inputs a non numeric value?
do {
cin >> players;
good_value = cin.good() && players >= 0 && players <= 2;
//good_value is true if we got valid input and the correct number of players
if( !good_value ) {
cout << "invalid number please reenter the number of players\n";
cin.clear(); //reset the streams state incase it was corrupted
}
} while( !good_value );
do {
cin >> player;
if( cin.good() && player >= 0 && player <= 2 )
break; //leave loop
cout << "invalid number please reenter the number of players\n";
cin.clear();
} while(true); //loop until break is called
well the cin.clear(); did not work alone. did some digging though and found that by using a string variable I was able to extract the bad input and then cin worked fine! Thanks for leading me on the wright path!
this is how my code looks now:
do {
cin >> players;
if( cin.good() && players >= 0 && players <= 2 )
break; //leave loop
cout << "invalid number please reenter the number of players\n";
cin.clear();
cin >> badChars;