在 do-while 循环中输入验证的 C++ 错误

标签 c++ do-while

我正在为学校项目创建一个非常简单的数字猜谜游戏,但在重复主菜单时遇到了问题。我使用do-while 循环 创建它,我遇到的问题是菜单选择变量是一个int,所以当我(或用户)输入从菜单中选择 }while(condition) 时意外输入的 non-int 在主循环结束时无法捕获它,程序会无限重复。相反,如果您在菜单选择时输入了一个无效整数,程序会捕获它并显示“无效输入”消息,然后重复主菜单。

很难用书面形式准确解释我的意思,所以这里是源代码,相关行用星号表示。我保存为 .cpp 并在 Linux 中使用 g++ -ansi -pedantic -Wall -Werror 进行编译老师禁止在条件语句中进行硬编码,因此使用全局常量。

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int PLAY = 1, HIGH_SCORE = 2, EXIT = 3;
const char YES = 'y', NO = 'n';

int main()
{
// Randomly generated value
  int randomNumber;
// User input
  int userGuess, menuChoice;
  char repeat;
// Calculated value
  int numberOfGuesses;
// Place-holder values (to be replaced by calculated values)
  int score1 = 1000, score2 = 2000, score3 = 3000;

  cout << endl << endl;
  cout << "Greetings! This is a number guessing game where I think of" << endl
       << "a whole number between one and ten and you try to guess it!" << endl
       << "You can guess as many times as you like, so don't be afraid" << endl
       << "to use trial and error, but your score is based on the " << endl
       << "number of guesses you make (the lower the better) so don't " << endl
       << "guess too haphazardly. Remember, only guess whole numbers!" << endl
       << endl;

  do
  {
    cout << endl << "Main menu." << endl
         << "1. Play game" << endl
         << "2. Display high scores" << endl
         << "3. Exit game" << endl
         << "Please select an option: ";
    cin >> menuChoice;

    if (cin.fail()){     
      cout << "Please enter a valid choice" << endl;
      continue;
    } 
    cin.ignore();

    switch(menuChoice)
    {
      case PLAY:
      do
      {
        unsigned seed = time(0);
        srand(seed);
        randomNumber = 1 + rand() % 10;

        cout << endl << "Press enter when you're ready to begin!";
        cin.ignore();
        cout << "Ok I thought of one!" << endl << endl;

        numberOfGuesses = 0;

        do
        {
          numberOfGuesses++;

          cout << "Enter your guess: ";
          cin >> userGuess;
          cin.ignore();

// Check user's guess
          if (userGuess == randomNumber)
            cout << "Correct! That was impressive!" << endl << endl;
          else if (userGuess < randomNumber)
            cout << "Not quite, you guessed low." << endl << endl;
          else if (userGuess > randomNumber)
            cout << "Not quite, you guessed high." << endl << endl;
        }while (userGuess != randomNumber);

        cout << "Your score for this game was " << numberOfGuesses << endl;

// Determine if a high score was beaten
        if (numberOfGuesses <= score1)
        {
          score3 = score2;
          score2 = score1;
          score1 = numberOfGuesses;
          cout << "That's a new all time high score!" << endl;
        }
        else if (numberOfGuesses <= score2)
        {
          score3 = score2;
          score2 = numberOfGuesses;
          cout << "That's a new high score!" << endl;
        }
        else if (numberOfGuesses <= score3)
        {
          score3 = numberOfGuesses;
          cout << "That's a new high score!" << endl;
        }
        else
        {
          cout << endl; 
        }

        cout << "Would you like to play again? y/n: ";
        cin.get(repeat);
        cin.ignore();

        while (tolower(repeat) != YES && tolower(repeat) != NO)
        {
          cout << endl;
          cout << "Sorry, that is an invalid choice." << endl
               << "Please enter 'y' for yes or 'n' for no: ";
          cin.get(repeat);
          cin.ignore();
        }
      }while (tolower(repeat) == YES); 
        break;

      case HIGH_SCORE:
      cout << endl << "High Score 1: " << score1 << endl
           << "High Score 2: " << score2 << endl
           << "High Score 3: " << score3 << endl << endl;
      cout << "Press enter to continue. ";
      cin.ignore();
        break;

      case EXIT: 
      cout << endl << "Thanks for playing, I'll see you next time!" << endl << endl;
        break;

      default:
      cout << endl << "That is an invalid selection, please enter '1', '2' or '3'"
           << endl;
        break;
    } 
  }while (menuChoice != EXIT);

  return 0;
}

根据当前答案编辑代码。

如果您需要更多信息,请告诉我,在此先感谢!

最佳答案

像这样使用 cin.fail()(而不只是 cin >> menuChoice;)(模仿 this post ):

cin >> menuChoice;
if (cin.fail()) {
  cout << "Please enter a valid choice" << endl;
  cin.clear();
  cin.ignore();
  continue;
}
//Remove the cin.ignore() at this place!

有关更多详细信息,请参阅 this SO thread

关于在 do-while 循环中输入验证的 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368810/

相关文章:

c++ - 我认为 do while 正在进入无限循环。或数组。 (运行时错误)

c++ - 如何编写析构函数来编译代码并释放所有分配的内存?

c# - 如何从服务器中的客户端池中识别客户端 - 设计

java - 如何将输入的计算存储到内存、输入重复、输入的第一个计算添加到输入的第二个计算等等?

c - do..while 循环 - 当条件满足时不中断

c# - While 语句 - 键入击键后控制台输出奇怪

c - 我在 do/while 循环中有一段时间,但它仍然告诉我我没有

c++ - 回调参数 C++ 中的协方差

c++ - 返回静态变量时static const和static的区别

c++ - 比较 C++ char* 字符以解析 .OBJ 文件