-
Exceptions in bad stream
Hello,
if a user was to enter a letter instead of an integer, the loop goes wild.
I know how to get rid of that error
cin.clear() and cin.ignore()
but I haven't been able to understand why it happens. A character is represented by an integer from 0 to 255. And each number is 32 bit enough for the integer variable to handle..so why does the stream fail then?
Is it possible to use exception to test for this errors, I am trying to understand exceptions, and I wasn't able to write code for that..
Thanks
-
When you input an integer, the allowed characters are 0 to 9 inclusive.
When you type in 123, you expect 123
Not some large number generated from the ASCII values 49(for '1'), 50(for '2'), 51(for '3')
So if you type in "Hello" when you're expecting an integer, then yes the stream goes into the fail state.
-
oh wow..yeah I think see you what you mean..
it makes sense for "Hello" or a string but not if i type a single character..'a' is enough to send the loop going crazy..so it still makes little sense to me :(
how is it that '0' to '9' are the allowed characters..it isn't possible for a user to enter input a numeric character...?
-
Strictly speaking, 'a' is an integer in the compiler's eyes. However, 'a' is not semantically an integer.
It makes no sense to store an 'a' in an integer, because 'a' is a letter, not a number.
-
ah right..makes sense then. Thanks