【问题标题】:C++ input validationC++ 输入验证
【发布时间】:2014-10-29 05:40:48
【问题描述】:

我正在开始 C++ 编程,并且必须进行大量输入验证。我发现这个功能似乎普遍适用,但在一个方面遇到了麻烦;如果我输入 -90,程序不会出错。我的问题是: 1.如何添加输入不能

感谢您的任何帮助或建议。

#include <ios>  // Provides ios_base::failure
#include <iostream>  // Provides cin

template <typename T>
T getValidatedInput()
{
    // Get input of type T
    T result;
    cin >> result;

    // Check if the failbit has been set, meaning the beginning of the input
    // was not type T. Also make sure the result is the only thing in the input
    // stream, otherwise things like 2b would be a valid int.
    if (cin.fail() || cin.get() != '\n')
    {
        // Set the error state flag back to goodbit. If you need to get the input
        // again (e.g. this is in a while loop), this is essential. Otherwise, the
        // failbit will stay set.
        cin.clear();

        // Clear the input stream using and empty while loop.
        while (cin.get() != '\n')
            ;

        // Throw an exception. Allows the caller to handle it any way you see fit
        // (exit, ask for input again, etc.)
        throw ios_base::failure("Invalid input.");
    }

    return result;
}

用法

inputtest.cpp

#include <cstdlib>  // Provides EXIT_SUCCESS
#include <iostream>  // Provides cout, cerr, endl

#include "input.h"  // Provides getValidatedInput<T>()

int main()
{
    using namespace std;

    int input;

    while (true)
    {
        cout << "Enter an integer: ";

        try
        {
            input = getValidatedInput<int>();
        }
        catch (exception e)
        {
            cerr << e.what() << endl;
            continue;
        }

        break;
    }

    cout << "You entered: " << input << endl;

    return EXIT_SUCCESS;
}

【问题讨论】:

  • 可选参数指定 T 的有效范围?
  • 您在getValidatedInput 中的错误处理是错误的。如果输入来自文件(由于重定向)并且您有文件结尾怎么办?
  • -90 是一个有效的int,所以你的函数失败会有点令人惊讶......话虽如此,有很多方法可以解析 specific 输入正确性。至于“通用验证”,我什至不知道您为什么需要这样的功能。阅读输入,检查cin,你有你的验证......
  • 这是编程初学者不幸的共同障碍——处理手动控制台输入。这在职业生涯中通常不会成为问题(控制台程序可能会被编写脚本,而手动输入通常使用 GUI)。这很乏味,容易出错,并且会分散实际任务的注意力。不过,在剩下的少数情况下需要强大的错误处理——我只是想安慰你。

标签: c++ validation input


【解决方案1】:

我希望这就是你所追求的,它会在输入零时退出,但会显示负数。由于输入catch方法抛出异常错误。

#include "stdafx.h"
#include <iostream>

using namespace std;

void inputcatch()
{
    cin.clear();
    cin.ignore(cin.rdbuf()->in_avail());
}

int main()
{
    int input;
    bool quit = false;
    while (!quit)
    {
        cout << "Enter number" << endl;
        cin >> input;
        if (cin.fail())
        {
            inputcatch();
            cout << "incorrect input" << endl;
        }
        else if (input == 0)
        {
            quit = true;

        }
        else
        {
            cout << "your number: " << input << endl;
        }
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    std::istream::operator &gt;&gt; 是根据 strtol、strtoul 和 cousins* 定义的,不幸的是,即使对于无符号类型,它们也总是接受减号。

    基本上你所能做的就是接受有符号的 int 输入并将结果与​​零进行比较。 std::cin.setf( std::ios::failbit ) 人为地引发了转换异常,因此您可以在某种程度上模拟转换函数在错误时的行为方式,但这可能并没有太大帮助。

    * operator &gt;&gt; 是根据std::num_get 定义的,它是根据scanf 定义的,它是根据strto* 定义的。每个人都只是推卸责任,但strtoul 肯定是有缺陷的。

    【讨论】:

      【解决方案3】:

      你可以使用函数来验证

      template <typename T>
      T getValidatedInput(function <bool(T)> validator) {
          T tmp;
          cin >> tmp;
          if (!validator(tmp)) {
              throw ios_base::failure("Invalid input.");
          }
          return tmp;
      }
      

      用法

      int input = getValidatedInput<int>([] (int arg) -> bool {
          return arg >= 0;
      });
      

      【讨论】:

        【解决方案4】:
        1. 使用 unsigned int 作为模板参数。
        2. 只有您可以设置关于哪些输入有效和哪些无效的规则。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-06
          • 2012-11-02
          • 2012-10-11
          • 2016-10-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多