2014-02-18 37 views
1
#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时,进入无限循环为什么我的程序在输入字符时会出现无限循环?

+0

你在使用,因为我不能复制VS2010下,即使是在HTTP编译:// ideone .COM/C88qG3? – herohuyongtao

+0

@herohuyongtao g ++和我在终端 – user2988803

回答

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 
} 
+0

这样做我还没有走这么远到编码在我的代码中使用此代码。我只是需要知道我的循环在哪里,所以我可以修复它 – user2988803

+1

**是**是什么导致你的无限循环。你有无效的输入,所以当你做while的条件时,它不会停止循环,将它发送到循环的顶部,输入已经在缓冲区中,所以它重复...永远。 –

+0

如果我声明userInput为“char userInput”,我仍然得到一个无限循环 – user2988803

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语句是这样的:switch(userInput - '0')

+0

我还没有深入到编码中去在我的代码中使用这段代码。我只需要知道我的循环在哪里,所以我可以修复它 – user2988803

+0

@ user2988803查看我的更新。 – turnt

+0

我做了编辑,但我无法退出程序后,它问我,如果我想再次玩...就像我会输入N或N,我不能退出程序 – user2988803

相关问题