【发布时间】: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