0

我需要弄清楚如何验证 2 个条件。

  1. 检查之前的号码是否已播放。
  2. 检查数字是否在 1 到 9 之间。

无论哪种情况,它都应该循环回到开头。在第一种情况下,它不应该运行,直到用户输入一个尚未播放的数字。

do
{
  cout << "Interesting move, What is your next choice?: ";
  cin >> play;
  Pused[1] = play;

  if(play != Pused[0] && play != cantuse[0] && play != cantuse[1] )
  {
    switch(play)
    {
      default:
        cout << "Your choice is incorrect\n\n";
        break;
    }   
  }
}while(play != 1 && play != 2 && play != 3 && play != 4
    && play != 5 && play != 6 && play != 7 && play != 8 && play != 9);

Dis_board(board);
4

1 回答 1

0

我喜欢使用无限循环+break语句的组合,而不是 do-while 循环,如下所示:

cout << "What is your first choice? ";
while (true)
{
    // Input the choice, including validation

    // Do the move

    if (game_over)
        break;

    cout << "Interesting move; what is your next choice? ";
}

在上面的代码中,两个注释代表代码,它本身可能包含循环。为了减少混淆,您可能希望将此代码填充到单独的函数中。例如,输入选项:

while (true)
{
    cin >> play;
    bool is_illegal =
        play == cantuse[0] ||
        play == cantuse[1] ||
        play < 1 ||
        play > 9;
    if (is_llegal)
        cout << "Your choice is incorrect; please enter again: ";
    else
        break;
}

注意:要实现对用户错误的良好处理,您还必须考虑用户输入废话而不是数字的情况;查找istream::ignoreios::clear为此。

于 2012-12-19T18:21:40.900 回答