我的程序要求用户输入年龄,但我必须验证年龄,如果有一些字符输入以 int Age 形式输入,那么我必须抛出异常并要求用户再次输入年龄...
在我的程序中,我首先调用 inputAge() 函数,该函数询问用户年龄,然后我检查 cin 如果失败,然后抛出字符串“invalid”,并在 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;
}
当
cin.clear()
处于错误状态时,您需要使用 cin.ignore
和 cin
,将您的 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
处于错误状态时,您必须清除它才能重新使用它。请参阅cin.fail()
和cin.ignore()
上的this帖子