如何检查验证
how to check the validation
当我尝试给出像"Hello"这样的字符串输入时,它会产生错误。如何检查当我给出字符串输入字符串时,它应该要求我给出正确的输入?
int y,m,d,h,min,s;
do
{
cout<<" Please enter the year: ";
cin>>y;
}while(y < 1970 || y > 2020);
#include "iostream"
#include<limits>
using namespace std;
int input()
{
int y;
do
{
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(), 'n');
std::cout << "Give the year" << std::endl;
std::cin >> y;
}
while (std::cin.fail() || y < 1970 || y > 2020);
return y;
}
main()
{
int x = input();
}
如果输入无法转换为int
(在您的情况下(,则将failbit
设置为 std::cin
。这可以通过调用 cin.fail()
来检索。
std::cin >> y;
if (std::cin.fail()) {
std::cout << "data entered is not of int type";
}
您也可以使用 !std::cin
代替 std::cin.fail()
。
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- 检查节点的输入验证的整数
- 验证(使用 static_assert)元组类型是否遵循某种顺序(有状态编译时检查)
- 强制输入通过验证检查
- 如何检查验证
- JSON 请求在名称验证检查期间忽略''
- 检查串行端口信息/描述以验证正确的端口
- 在数组中输入5个元素,检查验证,然后输出C++
- 验证代码以检查数字是否为回文
- 是否可以使用Boost概念检查库验证方法返回类型
- 如何实现旋转框的验证器来检查是否(n mod k == 0)
- 是否执行decltype内的表达式,或者只是检查是否验证
- c++模板检查类型验证
- 数组边界检查和输入验证
- QT快速或c++检查有效的电子邮件输入(电子邮件格式验证器)
- 如何进行良好的验证来检查输入是数字