如何检查验证

how to check the validation

本文关键字:验证 检查 何检查      更新时间:2023-10-16

当我尝试给出像"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()