I am trying to call a function which has a try catch block inside, but it enters in some kind of infinite loop.If cin.fail() I want to catch the error and then read again the number,but instead it keeps going over and over into a infinite loop.
I would really appreciate some help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void check_exception(cofetaria* add)
{
int nr{ 0 };
try {
cin >> nr;
if(cin.fail())
throw 1;
else {
add->set_pret(nr);
}
} catch(int err) {
cout << " You have to enter a number" << endl;
return;
}
}
void check_exception(cofetaria* add)
{
int nr{ 0 };
try
{
cin >> nr;
if (!cin) // <--- A better choice for checking all the state bits. Not just 1.
throw 1;
else
{
add->set_pret(nr);
}
}
catch (int err)
{
cout << " You have to enter a number" << endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
return;
}
}
The function would not cause an endless loop in its-self, but may be setting up an endless loop elsewhere because you did not reset the state bits on "cin".
For an endless loop problem I would look at the function call and what is around it.
I was thinking about the function and wondering if this is for a school assignment or something else?
If it is for school it helps to post the instructions that you were given, so those responding can know what you have to do and more to the point whar you have to use.
The "try/catch" works, but seems to be over done, unless it is required. There are other ways to check if "cin" has failed.
With out the rest of the code it is hard to say what would work best.