5
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 exceptions and "defensive programming".
Both the workbook and the exercise itself make apology to the use of std::cin.fail()
to identify invalid data and treat it within a try...catch
. So far so good - I’ve even completed the exercise - and everything works as proposed.
However, neither the workbook nor the exercise or any other resource I could find gives satisfactory details so that I can measure the criterion which causes the error flag on std::cin
. In the documentation of C++ found explanation about the existence of error flags returned by function fail()
, including about 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 a const char*
/string
in a variable of type int
.
That is correct?
[Bonus]: If you’re right, and I’m storing in a string
, what could be considered a failure condition (failbit
) or error (badbit
) to the istream
? How could it be possible to cause this mistake?
Remembering that this is a purely educational example. The purpose in the exercise was to use
std::cin.fail()
to treat simple mistakes but curiosity made me want to expand the context (so it helps to know what the limitations of this technique, advantages/disadvantages). Thank you!
cppreference is a better place to search for information about C++.
– Mário Feroldi
I think your understanding is correct. Complementando com o que está descrito em cppreference (linkada por @MárioFeroldi), failbit indica uma “falha de conversão de tipos” ou “nenhum caracter lido”, enquanto que badbit tem mais a ver com erros de escrita como “disco cheio”, “falha ao alocar memória”etc. To increase confusion, some operations can set several bits at once and fail() tests both failbit and badbit... (as I am only confirming your assumption and do not have time to do some tests, I posted only as a comment)
– marcus