TITLE: using cin to read numbers (Newsgroups: comp.lang.c++, 16 Dec 96) FRANZ: Paul A. Franz, P.E. (franzpa@nwlink.com) wrote: : I am using the Easywin target with borland C++ 4.51. If keyboard input : is requested using cin and a decimal point is included in the input for a : float or a double an overflow error is generated. KUEHL: kuehl@kalkofen.informatik.uni-konstanz.de (Dietmar Kuehl) This is definitely an error in the library, if you use a floating point data type for insertion. FRANZ: : #include : int main() : { : int int1, int2; : cout << endl << "Type first integer: "; : cin >> int1; : cout << "Type second integer: "; : cin >> int2; : Another interesting observation is that if you enter a floating : point number (use a decimal point) at the request for an integer then the : program runs to completion requesting no more input whatsoever. KUEHL: This is correct behavior: The first integer is terminated at the decimal point. If the decimal point is precided by a digit, the read of the first integer succeeds and leaves the stream with the decimal point as next character. Otherwise, i.e. if the decimal point is type in as the first character, as in ".75", even the read of the first integer fails: Integers are composed of digits only (well, for hexadecimal format there is an exception, but I ignore this here...). Reading only integers will never extract the decimal point. Instead, the read fails: Try it with a program modified to read an integers like this: int int1 = 0; // I initialize all variables on declaration... for (cin >> int1; cin.fail(); cin >> int1) { cin.clear(); // clear the error bits of the stream cin.ignore(INT_MAX, '\n'); // clear the remainder of the line if (cin.eof()) // yuk, hit and of file! /* error processing goes here...*/ exit(1); cout << "read of integer fail. try again: " << flush; } The constant 'INT_MAX' is declared in '' (the C++ standard name of this header is '' but this is not yet supported by all compilers). Actually, instead of 'INT_MAX' something else, namely 'numeric_limits::max()' from '' should be used but this is also not yet implemented by many C++ libraries... FRANZ: : Is this a known bug in the Easywin target for BCC 4.51 or is it something : I am doing? I have BCC 4.51 installed on 4 different computers and all : produce the same result. KUEHL: No, this is a bug in the use of the IOStream library: The user does not work correctly :-) Although this kind of error processing is a little awkward at first, it turns out to be quite reasonable to catch many kinds of error. FRANZ: : Any ideas? Please post for all to see and send e-mail as I will then get : the answer asap. KUEHL: I guess you are going to write an FAQ like summary (i.e. an answer to the question: "If a float is entered instead of an int, no more input is accepted. Why?") of the answers you get sent and post this. Can I use this answer in an FAQ like compilation of IO questions? Thank you in advance :-)