C++输入验证

C++ input validation

本文关键字:验证 输入 C++      更新时间:2023-10-16

我正在开始C++编程,必须进行大量的输入验证。我发现这个函数似乎普遍适用,但在一个方面遇到了问题;如果我输入-90,程序不会出错。我的问题是:1.如何添加输入不能<=的情况0?2.是否有更好的方法来限制用户输入?也许是C++中的库?

谢谢你的帮助或建议。

#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;
}

您可以使用函数来验证

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;
});

std::istream::operator >>是根据strtolstrtoul和表亲*定义的,不幸的是,即使对于无符号类型,它们也总是接受减号。

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

*根据std::num_get定义operator >>,根据scanf定义strto*。每个人都推卸了责任,但strtoul肯定有缺陷。

  1. 使用unsigned int作为模板参数
  2. 只有您可以设置关于哪些输入有效,哪些无效的规则

我希望这就是你想要的,它在输入0时退出,但会显示负数。由于输入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;
}