在 C++ 中验证来自用户的整数输入
Posted
技术标签:
【中文标题】在 C++ 中验证来自用户的整数输入【英文标题】:Validating integer input from user in c++ 【发布时间】:2018-10-27 05:57:58 【问题描述】:我的程序要求用户输入年龄,但如果有一些字符输入进入 int 年龄,我必须验证年龄,然后我必须抛出异常并要求用户再次输入年龄...
在我的程序中,我首先调用 inputAge() 函数来询问用户年龄,然后我检查 cin 是否失败,然后我抛出字符串“无效”并在 catch 块中调用 inputAge () 函数再次执行,但它进入了无限循环。
请有人告诉我我错在哪里或者我必须为此做些什么......
提前致谢!
#include<exception>
#include<iostream>
using namespace std;
class MyException: public exception
string msg;
public:
MyException()
void setError(string msg)
this->msg=msg;
const char* what()
return msg.c_str();
;
class UserData
int age;
long income;
string city;
int wheeler;
public:
void inputAge()
try
cout<<"Enter age: ";
cin>>age;
if(!cin)
throw "invalid";
else
if(age < 18 || age > 55)
MyException e;
e.setError("User has age between 18 and 55 ");
throw e;
catch(MyException &e)
cout<<e.what()<<endl;
inputAge();
catch(const char* msg)
cout<<msg;
inputAge();
void inputIncome()
try
cout<<"Enter income: ";
cin>>income;
if(income < 50000 || income > 100000)
MyException e;
e.setError("User has income between Rs. 50,000 – Rs. 1,00,000 per month");
throw e;
catch(MyException &e)
cout<<e.what()<<endl;
inputIncome();
void inputCity()
try
cout<<"Enter city with first letter capital: ";
cin>>city;
if(city != "Pune" && city != "Mumbai" && city != "Bangalore" && city != "Chennai")
MyException e;
e.setError("User stays in Pune/Mumbai/Bangalore/Chennai");
throw e;
catch(MyException &e)
cout<<e.what()<<endl;
inputCity();
void inputVehicle()
try
cout<<"Enter vehicle (2-wheeler or 4- wheeler): ";
cin>>wheeler;
if(wheeler == 2)
MyException e;
e.setError("User must have 4 wheeler");
throw e;
catch(MyException &e)
cout<<e.what()<<endl;
inputVehicle();
void display()
cout<<"****User details****"<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Income: "<<income<<endl;
cout<<"City: "<<city<<endl;
cout<<"vehicle: "<<wheeler<<" wheeler"<<endl;
;
int main()
UserData ud;
ud.inputAge();
ud.inputIncome();
ud.inputCity();
ud.inputVehicle();
ud.display();
return 0;
【问题讨论】:
使用 if ( cin.fail ( ) ) .... except if( !cin ) ...... 我试过了,但是没用 【参考方案1】:当cin
处于错误状态时,你需要使用cin.clear()
和cin.ignore
,将你的inputAge()函数改成这样:
void inputAge()
try
cout<<"Enter age: ";
cin>>age;
if(cin.fail())
cin.clear(); //YOU MUST CLEAR THE ERROR STATE
cin.ignore();
throw "invalid";
else
if(age < 18 || age > 55)
MyException e;
e.setError("User has age between 18 and 55 ");
throw e;
catch(MyException &e)
cout<<e.what()<<endl;
inputAge();
catch(const char* msg)
cout<<msg;
inputAge();
当std::cin
处于错误状态时,您必须在重新使用它之前清除它。请参阅thiscin.fail()
和cin.ignore()
上的帖子
【讨论】:
但是如果我在 int age 中输入 "abc" 字符串,那么它会抛出 3 次异常并打印 3 次无效消息!cin.ignore();
ing 一个字符可能还不够。我认为你必须忽略整行。以上是关于在 C++ 中验证来自用户的整数输入的主要内容,如果未能解决你的问题,请参考以下文章