In a C ++ exercise, it is proposed to store a data (numeric, integer - eg, 4
or -3650
) entered by the user through the console. This is an exercise to deal with exception handling and "defensive programming."
Both the handout and the exercise itself apologize to the use of std::cin.fail()
to identify an invalid die and treat it within try...catch
. So far so good - I've even completed the exercise - and everything works as intended.
However, neither the handout nor the exercise or any other feature I could find gives satisfactory details so I can gauge the criterion that causes the error flag in std::cin
. In the C ++ documentation I found an explanation for the existence of the error flags returned by the function fail()
, including failbit
and badbit
- but I was in doubt about the " internal logic of the operation itself".
By observation and according to the section below:
failbit is generally set by an operation when the error is related to the internal logic of the operation itself
If we consider:
int x = 0;
std::cout << "Digite um número: ";
cin >> x; // stackoverflow
if (std::cin.fail()) {
std::cout << "A operação falhou porquê tentei armazenar uma string em int\n";
}
I understand that std::cin.fail()
would return true
( failbit
) in this case why we tried to store const char*
/ string
into a variable of type int
.
Is that correct?
[Bonus]: If it is correct, and I am storing it in a string
, what could be considered a failure condition ( failbit
) or error ( badbit
) to istream
? How could this error be caused?
Remembering that this is a purely educational example. The purpose of the exercise was to use
std::cin.fail()
to handle simple errors but curiosity made me want to expand the context (so it helps to know the limitations of this technique, advantages / disadvantages). Thanks!