M
M
Meliborn2011-02-25 01:30:56
C++ / C#
Meliborn, 2011-02-25 01:30:56

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 &gt;&gt; var;<br/>
}<br/>
catch(std::exception& e)<br/>
{<br/>
cout &lt;&lt; &quot;Ошибка ввода!&quot;;<br/>
}<br/>

In case of an error, the text is displayed, but the application ends there. How to be? I just can't figure out try catch :(
The application is a simple console.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
G
gaelpa, 2011-02-25
@gaelpa

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)

S
superhabra, 2011-02-25
@superhabra

try
{
cin >> var;
}
catch(std::exception&e)
{
cin.clear();
cout << "Input error!";
}

D
Dzuba, 2011-02-25
@Dzuba

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);

G
gaelpa, 2011-02-25
@gaelpa

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').

S
SkyKos, 2011-02-25
@SkyKos

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
}

A
Alexey Grichenko, 2011-02-25
@Kalobok

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 question

Ask a Question

731 491 924 answers to any question