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

do-while ループの代わりに、次のように無限ループ +breakステートメントの組み合わせを使用するのが好きです。

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? ";
}

上記のコードでは、2 つのコメントはコードを表しており、それ自体にループが含まれる場合があります。混乱を避けるために、このコードを別の関数に詰め込みたいと思うかもしれません。たとえば、選択肢を入力するには:

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::ignoreくださいios::clear

于 2012-12-19T18:21:40.900 に答える