【问题标题】:How do I validate input without exiting my do while loop?如何在不退出 do while 循环的情况下验证输入?
【发布时间】:2016-06-09 00:30:23
【问题描述】:

我正在开发一个程序,该程序通过输入 1-3 的整数(4 退出)提示用户从 3 个不同的选项中进行选择。我需要编写一个代码来验证输入是否为整数,如果它不是整数则重新提示它们。这是我的代码的基本思想(完整发布太长了)。

do 
{
cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
}while (first_input!=4)

然后我有多个 if 语句,它们根据用户选择的选项执行表达式。稍后我还会提示他们在代码中输入其他整数值。

如果用户输入未能输入整数而是输入字符,我该如何让用户返回菜单?约束:不能使用continuebreak

提前致谢。

【问题讨论】:

    标签: c++ validation loops input do-while


    【解决方案1】:

    您可以尝试使用 goto 标签。

    do{
       label:
            // your code
    if(check) goto label;
    }while(check);
    

    【讨论】:

      【解决方案2】:

      如果您想在输入非整数的情况下回到开头,也许这样的事情会起作用?

      // Insert after "cin >> first_input;"
      if (cin.fail()) {
          // Handle non-int value.
      
          // Clear error flag.
          cin.clear();
      
          // Empty buffer up to next newline.
          cin.ignore(numeric_limits<streamsize>::max(), '\n');
      
          // Complain & restart.
          cout << "Invalid input.  Please try again." << endl;
          continue;
      }
      

      这样做是清除错误标志,清除缓冲区,然后返回开始。 cin.ignore() 不需要明确传递 std::numeric_limits&lt;std::streamsize&gt;::max() 作为其第一个参数;但是,如果出现错误,我更愿意这样做以确保错误输入消失。请注意,std::numeric_limits 是在标准标头 &lt;limits&gt; 中定义的,并且需要包含它。

      【讨论】:

      • 谢谢!非常感谢您的帮助。
      【解决方案3】:
      do 
      {
          cout << "Menu: Please select one of the following options:" << endl;
          cout << " 1 - Drop a single chip into one slot." << endl;
          cout << " 2 - Drop multiple chips into one slot." << endl;
          cout << " 3 - Drop 5 chips into each slot." << endl;
          cout << " 4 - Quit the program." << endl;
          cout << "Enter your selection now: ";
          cin >> first_input;
          //lets say if user enters value out of range. then want to show menu again.
          if(first_input > 4) {
              cout << "Invalid input "<<endl;
              continue;
          }
          // you can do other stuff here. 
          // ...
      }while (first_input!=4)
      

      【讨论】:

      • 这不能解决 OP 的问题“如果用户输入未能输入整数而是输入字符,我如何将用户送回菜单?
      【解决方案4】:

      您正在寻找 continue 关键字。

      【讨论】:

      • 感谢您的快速回复。还有其他方法吗?虽然我很肯定会解决它,但我必须不要使用continue
      • @T.Rydalch:什么或谁需要?如果您对“允许”使用哪些 C++ 有任意限制,如果您下次在问题中预先说明这一点,而不是等到我们已经写好答案,我将不胜感激。 ...
      • 正式注明。我的课程导师。
      • @T.Rydalch:所以这是一个学校作业。大概目的是让您自己提出这个想法!不要让互联网上的人为你做这件事......
      • 考虑嵌套循环。
      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 2023-04-08
      • 2016-04-07
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      相关资源
      最近更新 更多