【问题标题】:How to check whether a user has entered the wrong value when navigating through a Terminal I/O?如何在终端 I/O 导航时检查用户是否输入了错误的值?
【发布时间】:2016-09-28 06:48:35
【问题描述】:

这是一个执行终端 IO 导航技术的示例程序。我正在尝试检查用户是否输入了错误的值。

// This program simply demonstrates nagivating through a Terminal I/O
// whilst checking that the user has not entered the wrong value for nagivation

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string user_input;

    cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?";
    cin >> user_input;
    // Here I would like to check whether the user has entered some wrong value - say "e", "f", or even "glirebglhbgeriuub",
    // and if they have entered the wrong value, they get an error message and asked to enter again
    // I would also like to know how to use a more generic incorrect user input detection method
    // Any ideas?

    # Do other things here depending upon whether the result was "W" or "D"...

    return EXIT_SUCCESS;
}

编辑:这是我过去尝试过的,但我不确定这是否是最好的方法:

cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?" << endl;
cout << "-> ";
cin >> user_input;

while ((user_input != "W") && (user_input != "D"))
{
    cout << "Would you like to withdraw (W) from or deposit (D) into your Bank Account?" << endl;
    cout << "-> ";
    cin >> user_input;
}

if (user_input == "W")
{
    // DO STUFF
}
else if (user_input == "D")
{
    // DO STUFF
}

【问题讨论】:

  • 到目前为止您尝试了哪些方法,为什么没有成功?
  • 我已经看到了多种解决此问题的方法,其中大多数涉及使用一种形式的 while 循环。我很好奇在检查用户是否输入正确的输入时是否有某种“标准”。
  • " 我很好奇是否有某种“标准”" 不,没有。你做最适合你的事情。
  • 与其检查错误的值,不如检查正确的值,如果没有找到正确的值,就假设它是错误的。
  • 您追求的是特定的 c++ 语法吗?有很多方法可以做到这一点。查看“if”条件和“switch”语句。

标签: c++ input io terminal


【解决方案1】:

尝试使用条件语句:

if(user_input == "W")
{
   //do stuff
}
else if(user_input == "D")
{
   //do different stuff
}
else
{
   //invalid input message
}

仅根据您的问题,我不确定您有什么和没有尝试过什么,所以这里是用户输入清理的简单而甜蜜的解决方案。

【讨论】:

    【解决方案2】:

    您有不需要的重复代码。只需让用户 user_input 为空,这是明显的默认值,然后直接进入您的循环。

    std::string user_input;
    
    while ((user_input != "W") && (user_input != "D"))
    {
        cout << "Would you like to withdraw (W) from or deposit (D)"
                " into your Bank Account?\n-> ";
        cin >> user_input;
    }
    

    对我来说,第二个条件是多余的,基于 while 循环。

    if (user_input == "W")
    {
        // DO W STUFF
    }
    else { // if must be "D"
        // Do D stuff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多