C ++输入验证 [英] C++ input validation
问题描述
我正在开始C ++编程,并且必须做很多输入验证.我发现此功能似乎普遍适用,但是在一个方面遇到了麻烦.如果我输入-90,则程序不会给出错误.我的问题是:1.如何添加输入不能小于等于0的情况?2.有没有更好的方法来限制用户的输入?也许是C ++中的库?
I am beginning C++ programming, and have to do a lot of input validation. I have found this function that seems universally applicable, but am having trouble with one aspect; If I were to type -90, the program doesn't give an error. my question(s) are: 1. How can I add the circumstance that input cannot be <= 0? 2. Is there a better way to limit users input? Maybe a library within 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;
}
推荐答案
std :: istream :: operator>>
是根据 strtol
, strtoul
和表亲*,不幸的是,甚至对于无符号类型也总是接受减号.
std::istream::operator >>
is defined in terms of strtol
, strtoul
, and cousins*, which unfortunately all invariably accept a minus sign even for unsigned types.
基本上,您所能做的就是接受带符号的int输入并将结果与零进行比较. std :: cin.setf(std :: ios :: failbit)
人为地引发转换异常,因此您可以对转换函数在出现错误时应如何表现进行排序,但可能并非如此有很大帮助.
Essentially all you can do is accept signed int input and compare the result to zero. std::cin.setf( std::ios::failbit )
artificially raises a conversion exception, so you can sort-of emulate how the conversion function should behave on error, but that might not really be much help.
* operator>>
是根据 std :: num_get
定义的,而 scanf
定义的.根据 strto *
定义.每个人都刚刚通过,但是 strtoul
肯定是有缺陷的.
* operator >>
is defined in terms of std::num_get
, which is defined in terms of scanf
, which is defined in terms of strto*
. Everyone just passed the buck, but strtoul
is pretty surely defective.
这篇关于C ++输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!