c++ - Why does my program have an infinite-loop when I enter in a character? -
contains # lt; Iostream & gt; # Include & lt; Cstdlib & gt; # Include & lt; Ctime & gt; #include & lt; string & gt; using namespace std; Int main () {char replay; Int userInput; The court's & lt; & Lt; "Let's play rock, paper, scissors" & lt; & Lt; Endl; Taxes {cout & lt; & Lt; "Enter 1 for rock, 2 for paper, 3 for scissors" & lt; & Lt; Endl; CIN & gt; & Gt; user input; Switch (User Input) {Case 1: Cust & lt; & Lt; "You chose the rock" & lt; & Lt; Endl; break; Case 2: Cotton and LT; & Lt; "You chose paper" & lt; & Lt; Endl; break; Case 3: Cotton and LT; & Lt; "You chose the scissors" & lt; & Lt; Endl; break; Default: cout & lt; & Lt; User input & lt; & Lt; "Not a valid option" & lt; & Lt; Endl; break; } Cout & lt; & Lt; "Do you want to play again (for Y, not for N)?" & Lt; & Lt; Endl; Cin & gt; & Gt; Replay; } While ((Replay == 'Y') || (Replay == 'Y')); Return 0; }
When I enter a number in my answer to enter a number and when I am asked that I want to play again and I enter that character Which is not Y, N, or N goes into an infinite loop
users As input
is defined as an int
when you try to read int
, and actually what's in the stream This is a char
, it will fail (but still inside the char
) you have to clear the error status and ignore the bad input:
if (! (Cin> & gt; user input)) {cin.clear (); // error state clears cin.ignore (std :: numeric_limits & lt; std :: streamsize & gt; :: max (), '\ n'); // If input was valid then buffer} remove bad input from other {// code}
Comments
Post a Comment