【问题标题】:How can I avoid bad input from a user?如何避免用户的错误输入?
【发布时间】:2014-03-22 03:53:44
【问题描述】:

我是一个非常新手的程序员,所以我不太了解编写代码来保护应用程序。基本上,我创建了一个 basicMath.h 文件并创建了一个 do while 循环来制作一个非常基本的控制台计算器(只有两个浮点数通过函数)。我使用一系列 if 和 else if 语句来确定用户想要做什么。 (1.add, 2.subtract, 3.multiply, 4.divide) 我使用 else { cout

 `#include <iostream>
  #include "basicMath.h"

  using namespace std;
  char tryAgain = 'y';
  float numOne = 0, numTwo = 0;
  int options = 0;
  int main()
  {
   cout << "welcome to my calculator program." << endl;
 cout << "This will be a basic calculator." << endl;
 do{
    cout << "What would you like to do?" << endl;
    cout << "1. Addition." << endl;
    cout << "2. Subtraction." << endl;
    cout << "3. Multiplication" << endl;
    cout << "4. Division." << endl;
    cin >> options;
    if (options == 1){
        cout << "Enter your first number." << endl;
        cin >> numOne;
        cout << "Enter your second number." << endl;
        cin >> numTwo;
        cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
    }
    else if (options == 2){
        cout << "Enter your first number." << endl;
        cin >> numOne;
        cout << "Enter your second number." << endl;
        cin >> numTwo;
        cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
    }
    else if (options == 3){
        cout << "Enter your first number." << endl;
        cin >> numOne;
        cout << "Enter your second number." << endl;
        cin >> numTwo;
        cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
    }
    else if (options == 4){
        cout << "Enter your first number." << endl;
        cin >> numOne;
        cout << "Enter your second number." << endl;
        cin >> numTwo;
        cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
    }
    else {
        cout << "Error, invalid option input." << endl;
    }
    cout << "Would you like to use this calculator again? (y/n)" << endl;
    cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
 `

【问题讨论】:

  • 当然有办法——如果你发布你的代码,我们也许可以告诉你哪里出错了
  • 试试if (cin &gt;&gt; options) { // input was a number } else { // input was something else. }
  • 我不确定我明白你的意思吗?我应该在哪里添加 if ( cin >> options)?在我开始原始 if 语句之前?
  • 即把cin &gt;&gt; options替换成上面那个if语句。
  • +1 表示关注用户输入验证,尽管是新手程序员。

标签: c++


【解决方案1】:

一种方法是使用异常处理,但作为新手,您可能还远未学会。

改为使用cin.fail(),它在输入错误或意外输入后返回 1。请注意,您需要使用cin.clear() 清除“不良”状态。

一个简单的方法是实现一个函数:

int GetNumber ()
{
    int n;
    cin >> n;
    while (cin.fail())
    {
        cin.clear();
        cin.ignore();
        cout << "Not a valid number. Please reenter: ";
        cin >> n;
    }
    return n;
}

现在,无论您在哪里输入,在您的主函数中,只需调用 GetNumber 并将返回的值存储在您的变量中。例如,不要使用cin &gt;&gt; numOne;,而是使用numOne = GetNumber();

【讨论】:

  • 听说过do while 循环吗?
  • 当然可以,但是我必须将“无效数字”语句放在if (cin.fail()) 条件中,以避免在第一次迭代时显示它。我更喜欢这个。
【解决方案2】:

当您输入cin 时,它需要一个特定的类型,例如整数。如果它收到了它不期望的东西,例如一封信,它会设置一个bad 标志。

您通常可以通过查找 fail 来捕获它,如果找到它,请刷新您的输入以及坏位(使用 clear),然后重试。

【讨论】:

    【解决方案3】:

    先读取一整行文本,然后将该行文本转换为数字并处理字符串到数字转换中的任何错误。

    std::cin 读取整行文本是使用std::getline 函数完成的(不要与流的成员函数混淆):

    std::string line;
    std::getline(std::cin, line);
    if (!std::cin) {
        // some catastrophic failure
    }
    

    使用std::istringstream(C++11 之前)或std::stoi(C++11)完成字符串到数字的转换。这是 C++11 之前的版本:

    std::istringstream is(line);
    int number = 0;
    is >> number;
    if (!is) {
        // line is not a number, e.g. "abc" or "abc123", or the number is too big
        // to fit in an int, e.g. "11111111111111111111111111111111111"
    } else if (!is.eof()) {
        // line is a number, but ends with a non-number, e.g. "123abc",
        // whether that's an error depends on your requirements
    } else {
        // number is OK
    }
    

    这里是 C++11 版本:

    try {
        std::cout << std::stoi(line) << "\n";
    } catch (std::exception const &exc) {
        // line is not a number, e.g. "abc" or "abc123", or the number is too big
        // to fit in an int, e.g. "11111111111111111111111111111111111"
        std::cout << exc.what() << "\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多