在无效输入后重新提示用户-c++

Reprompt user after invalid input-c++

本文关键字:提示 用户 -c++ 新提示 无效 输入      更新时间:2023-10-16

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

void newGame()
{
    char newGameChoice = 'a';
    cout << "n--------------------------------------------------------------------------------" << endl;
    cout << "Press N to play a new gamen";
    cout << "Press X to exitnn";
    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();
    }
}

你的问题是:

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

你再次调用start(),它将再读取一个值到begin

在寻求帮助之前,请花更多的时间分析你的代码,这将帮助你成长为一个开发人员更多

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');
  }
}

你的部分问题是你的start()方法不是以最合乎逻辑的方式设计的。当前,当给出无效输入时,您将尝试读入另一个输入并再次调用start()。当您第二次调用start()时,它从start()方法的开头开始,不知道之前的输入。

你应该做的是,当给出一个无效的输入时,使用while()循环,直到输入正确的输入才继续。

void start() 
{
    ...
    //Get initial user input
    while begin != 'B'
    {
      Keep getting input if wrong
    }
    game(userIn, c);

}