C++输入验证
C++ input validation
我正在开始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 >>
是根据strtol
、strtoul
和表亲*定义的,不幸的是,即使对于无符号类型,它们也总是接受减号。
基本上,您所能做的就是接受带符号的int输入,并将结果与零进行比较。std::cin.setf( std::ios::failbit )
人为地引发了一个转换异常,因此您可以模拟转换函数在出错时的行为,但这可能并没有多大帮助。
*根据std::num_get
定义operator >>
,根据scanf
定义strto*
。每个人都推卸了责任,但strtoul
肯定有缺陷。
- 使用unsigned int作为模板参数
- 只有您可以设置关于哪些输入有效,哪些无效的规则
我希望这就是你想要的,它在输入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;
}
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- 正在验证c++中用户的整数输入
- cin 的十进制输入验证?
- 输入验证以筛选出字符、字符串和一系列整数
- 输入验证将数字放入向量中
- GoogleMock:如何验证输入参数的调用次数?
- 使用函数验证输入
- 如何验证输入仅是数字数字
- 提升灵气验证输入解析器
- 当循环不中断时,使用 cin.ignore 和 cin.clear() 来验证输入
- C++,如何验证输入的数据是否为正确的数据类型
- 验证输入
- 使用正则表达式验证输入
- 验证输入和getline()函数
- 函数验证输入c++简单
- C++如何验证输入以与重载>>运算符一起使用
- 在Windows c++应用程序中验证输入UTF-8序列
- 抵押计算器验证输入错误
- 验证输入的好方法是什么?