[英]Why does my program have an infinite-loop when I enter in a character?
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
int main()
{
char replay;
int userInput;
cout<< "Let's play Rock, Paper, Scissors"<<endl;
do
{
cout<<"Enter 1 for Rock, 2 for Paper, 3 for Scissors"<< endl;
cin>> userInput;
switch(userInput)
{
case 1:
cout <<"You chose rock" << endl;
break;
case 2:
cout <<"You chose paper" <<endl;
break;
case 3:
cout <<"You chose scissors" << endl;
break;
default:
cout << userInput << " is not a valid choice"<< endl;
break;
}
cout<<"Would you like to play again (Y for yes, N for no)?"<<endl;
cin >> replay;
} while((replay=='Y') || (replay=='y'));
return 0;
}
When I enter in a character in my answer for entering a number and when I'm asked if I want to play again and I enter in a character that isn't Y, y, N, or n it goes into an infinite loop 当我在输入数字的答案中输入一个字符时,当系统询问我是否要再次玩并且输入的字符不是Y,y,N或n时,它将陷入无限循环
userInput
is defined as an int
. userInput
定义为int
。 When you attempt to read an int
, and what is actually in the stream is a char
, it will fail (but the char
is still in the buffer). 当您尝试读取一个
int
,而流中实际包含的是char
,它将失败(但char
仍在缓冲区中)。 You must clear the error status and ignore the bad input: 您必须清除错误状态并忽略错误的输入:
if (!(cin >> userInput))
{
cin.clear(); // clears the error state
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // remove the bad input from the buffer
}
else
{
// the code if the input was valid
}
Just a suggestion, but I would rearrange your code as follows: 只是一个建议,但我会按以下方式重新排列您的代码:
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
int main()
{
char replay;
char userInputChar;
int userInput;
cout<< "Let's play Rock, Paper, Scissors"<<endl;
for(;;)
{
cout << "Enter 1 for Rock, 2 for Paper, 3 for Scissors"<< endl;
cin >> userInputChar;
userInput = userInputChar - '0';
switch(userInput)
{
case 1:
cout <<"You chose rock" << endl;
break;
case 2:
cout <<"You chose paper" <<endl;
break;
case 3:
cout <<"You chose scissors" << endl;
break;
default:
cout << userInput << " is not a valid choice"<< endl;
break;
}
cout<<"Would you like to play again (Y for yes, N for no)?"<<endl;
cin >> replay;
if((replay!='Y') || (replay!='y'))
break;
}
return 0;
}
Notice how I took care of converting the char
input to an int
. 请注意,我是如何将
char
输入转换为int
。
If you want to use your current loop declare userInput
as a char
and then make your switch statement like this: switch(userInput - '0')
如果要使用当前循环,
userInput
声明为char
,然后使switch语句如下: switch(userInput - '0')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.