From: Greg C. <gch...@sb...> - 2011-09-23 15:02:53
|
On 2011-09-23 00:54Z, Mani wrote: > > I see that for double input stored as ints, it works fine.. > > { > int x; > > cin >> x; > if(cin.fail()) { > cout << "Input failed" << endl; > } > cout << "x = " << x << endl; > } > > if the user enters 10.3 -- cin succeeds, and it works as expected... It should display "10". The reason is not that it reads 10.3 as a floating-point number (it doesn't); converts that floating-point value to an integer (again, no); and prints the integer. That's not what's happening. Instead, it reads "1" and "0", and stores them in a buffer; then reads "." and stops reading there because a decimal point cannot be part of an integer literal; then converts buffer contents "10" to an integer, and prints it; and leaves ".3" on the stream. > can you explain why the difference?? For std::cin >> some_int, input is read and converted as if by scanf(): i.e., characters are read one at a time, stopping at the first character that can't be part of an int value; any remaining characters are left on the input stream; and the characters that have been read (before the first invalid one) are converted to an int if possible; otherwise (e.g. if it's too large) failbit is set. For std::cin >> some_bool, a long int is extracted as above; if its value is either 0 or 1, then that value is assigned to the bool; otherwise, failbit is set. In both cases, int and bool, the operation fails if the destination cannot represent the result of converting the extracted characters to an integer. In the case of bool, that excludes everything but one and zero. If the stream contains "127.0.0.1", then "127" is extracted from the stream, and ".0.0.1" is not. This is a valid int, but not a valid bool. OTOH, if the stream contains "1x" or "0x", then std::cin >> some_bool assigns values of 1 or 0 respectively to the bool; but if it contains "10x", then nothing is assigned to the bool. It is prudent to check the stream state after such operations. |