【问题标题】:Dual validation with a do-while loop and if-else statement使用 do-while 循环和 if-else 语句进行双重验证
【发布时间】:2012-12-07 03:40:31
【问题描述】:

我需要弄清楚如何验证 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);

【问题讨论】:

  • 那么您的代码有什么问题?
  • 您真的应该将您的while 条件重写为while (play &gt; 0 &amp;&amp; play &lt; 10)...
  • @H2CO3: while (play &gt; 0 &amp;&amp; play &lt; 10)while(play != 1 &amp;&amp; [...] )相同
  • @Nawaz 忘记了 ! 操作符,但你没明白我的意思吗?
  • @H2CO3:我明白你的意思,但问题是我没有问这个问题。提问者需要理解你的意思,而不是你写的。 :-)

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


【解决方案1】:

我喜欢使用无限循环 + 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? ";
}

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

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

【讨论】:

  • 谢谢你!!!!!!!!!太感谢了!!!!!!!我非常感谢!如果有什么我能为你做的,请说出它的名字!
  • 我实际上不喜欢 while(true) 循环,在您阅读整个循环之前,您并不清楚您要做什么。我宁愿选择 while(!(play = read_move())) { ... }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 2019-04-24
  • 2015-11-08
  • 1970-01-01
  • 2015-04-07
  • 2014-07-01
  • 1970-01-01
相关资源
最近更新 更多