在无效的input-c ++之后重新提示用户

时间:2015-05-19 14:41:00

标签: c++ input

我修改了原始代码,前两个无效输入提示工作正常。当我在此提示中实现相同的逻辑以开始新游戏时,我的程序将无法识别无效输入,输入任何键将启动新游戏。

void newGame()
{
    char newGameChoice = 'a';

    cout << "\n--------------------------------------------------------------------------------" << endl;
    cout << "Press N to play a new game\n";
    cout << "Press X to exit\n\n";
    cout << "--------------------------------------------------------------------------------" << endl;

    cin >> newGameChoice;
    newGameChoice = toupper(newGameChoice);

    if (newGameChoice == 'N');
    {
        char userIn = 'a';
        char c = 'a';

        game(userIn, c);
    }

    while (newGameChoice != 'N' || 'X')
    {
        cout << "--------------------------------------------------------------------------------";
        cout << "\n         Invalid input. Please try again.\n" << endl;
        cout << "--------------------------------------------------------------------------------" << endl;
        newGame();
    }
}

3 个答案:

答案 0 :(得分:2)

你的问题是:

    if (begin != 'B');
    {
        ...
        cin >> begin;
        begin = toupper(begin);
        start();    <------

您再次致电start(),这会将另一个值读入begin

在发布求助之前,请花更多时间分析您的代码,这将有助于您成长为更多的开发者。

答案 1 :(得分:2)

while (newGameChoice != 'N' || 'X')

相当于

while (newGameChoice != 'N' || 'X' != 0)

也许你的意思是

while (newGameChoice != 'N' || newGameChoice != 'X')

编辑: 代码是错误的,必须重写,这是一个建议:

void newGame()
{
  char newGameChoice = 'a';
  while (true) {
    while (true) {
      cin >> newGameChoice;
      newGameChoice = toupper(newGameChoice);
      if (newGameChoice != 'X' && newGameChoice != 'N') {
        // Wrong input print error message
      } else {
        break;
      }
    }
    if (newGameChoice == 'X') {
      return;
    }
    game('a', 'a');
  }
}

答案 2 :(得分:0)

您的部分问题是您的start()方法并非以最合理的方式设计。目前,当给出无效输入时,您尝试读入另一个输入并再次调用start()。当您第二次调用start()时,它会在start()方法的开头重新开始,而不知道之前的输入。

您应该做的是在给出无效条目时使用while()循环,并且在输入正确的输入之前不要继续。

void start() 
{
    ...
    //Get initial user input

    while begin != 'B'
    {
      Keep getting input if wrong
    }

    game(userIn, c);

}

相关问题