C++如何检查输入年份的合理性

来源:百度知道 编辑:UC知道 时间:2024/05/05 15:48:11
从键盘读入要求输出日历的年份xxxx,此部分要求对读入的数据具有一定的错误检查能力,如输入的不是数字,或输入的是五位以上的年份等。如果不是,退出. 编写一个函数

下面这段代码可以判断是否输入的是数字,或者要小于10000,如果不合条件,可以进行循环输入,知道输入正确的为止。可以作为参考:

void judge()
{
int year;
cout<<"Input the year:";
while (1)
{
cin>>year;
if (cin.good()&&year>0&&year<10000)
break;
cout<<"The number you input is wrong!"<<endl;
cout<<"Please input again:";
cin.clear();
cin.sync();
}
}

#include<iostream>

int main()
{
unsigned int year(0);
std::cin>>year;
if(std::cin.good() && year<9999) std::cout<<"有效日期"<<std::endl;
else std::cout<<"无效日期"<<std::endl;
return EXIT_SUCCESS;
}