双输入验证C ++程序的麻烦

时间:2012-12-19 05:37:53

标签: c++ if-statement do-while

所以我想:

  1. 在do while循环中进行双输入验证
  2. 检查是否已完成移动以及是否为逻辑输入。 (#1-9)
  3. 我原本以为if else语句但我不确定如何使用else语句返回循环的开头。

    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;
        }   
      }
      else
      { }
    }    
    while(play != 1 && play != 2 && play != 3 && play != 4 && play != 5 && play != 6 && play != 7 && play != 8 && play != 9);
    Dis_board(board);
    

3 个答案:

答案 0 :(得分:0)

使用“continue”关键字返回循环开始。

答案 1 :(得分:0)

只需删除else即可。我认为这不是必需的。如果满足while中的条件,则会自动继续循环。

答案 2 :(得分:0)

你的问题有点难以理解,但你在这个循环中有一些条件需要解决:

  1. 询问用户输入
  2. 检查用户输入是否有效(1-9之间,之前未使用过)
  3. 如果我们有一个有效的选择,则退出循环
  4. 所以我们需要记录已完成的动作,并检查用户的输入是否在有效选择范围内,我们可以使用仅在选择有效选项时退出的循环。

    int choice;
    bool used[9] = { false }; // Set all values to false
    std::cout << "Interesting move, what is your next choice?: ";
    do {
        std::cin >> choice;
        // Here we check if the choice is within the range we care about
        // and not used, note if the first condition isn't true then
        // the second condition won't be evaluated, so if choice is 11
        // we won't check used[10] because the && will short circuit, this
        // lets us avoid array out of bounds. We also need to
        // offset the choice by 1 for the array because arrays in C++
        // are indexed from 0 so used runs from used[0] to used[8]
        if((choice >= 1 && choice <= 9) && !used[choice - 1]) {
            // If we're here we have a valid choice, mark it as used
            // and leave the loop
            used[choice - 1] = true;
            break; // Exit the loop regardless of the while condition
        }
    
        // If we've made it here it means the above if failed and we have
        // an invalid choice. Restart the loop!
        std::cout << "\nInvalid choice! Input: ";
    } while (true);