Answer the question
In order to leave comments, you need to log in
How to work with try - catch when checking input in C++?
There is a variable of type int, I do cin >> var. If the user enters a test, or something bad, then you need to display your error text without terminating the application. I try like this:
try<br/>
{<br/>
cin >> var;<br/>
}<br/>
catch(std::exception& e)<br/>
{<br/>
cout << "Ошибка ввода!";<br/>
}<br/>
Answer the question
In order to leave comments, you need to log in
The pointer in cin does not move on error.
1. as superhabra wrote, you need to remove failbit cin.clear()
2. you need to shift the pointer with something, for example cin.ignore(1)
try
{
cin >> var;
}
catch(std::exception&e)
{
cin.clear();
cout << "Input error!";
}
And the application ends somewhere else, outside of the try catch construct, right?
Possibly because var was never introduced.
It makes sense to immerse the construction in a loop, for example:
int var = 0;
do
{
try
{
cin >> var;
}
catch(std::exception& e)
{
cout << "Ошибка ввода!";
}
} while (var == 0);
And then, depending on what you need.
If the console is with manual input, then most likely you need to ignore before "\n" (like cin.ignore(100500,'\n').
Perhaps your application is exiting because there is nothing beyond the try-catch block. You can arrange the input as a loop, for example, like this:
std::string str;
while (std::cin >> str)
{
//Process string here
}
And what's next? Maybe it ends somewhere else. For example, where var is used with an incomprehensible value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question