当我输入一个角色时,为什么我的程序会有无限循环?

时间:2014-02-18 04:08:03

标签: c++ character infinite-loop do-while

#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; 

 }

当我在输入数字的答案中输入一个字符时,当我被问到是否要再次播放时,我输入的字符不是Y,y,N或n,它会进入无限循环

2 个答案:

答案 0 :(得分:3)

userInput被定义为int。当您尝试读取int时,流中的实际内容是char,它将失败(但char仍然在缓冲区中)。您必须清除错误状态并忽略错误输入:

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
}

答案 1 :(得分:1)

只是一个建议,但我会按如下方式重新安排您的代码:

#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; 

 }

请注意我如何处理将char输入转换为int

如果您想使用当前循环将userInput声明为char,然后按照以下方式生成切换语句:switch(userInput - '0')