TITLE: input minutia (Newsgroups: comp.std.c++) KANZE: kanze@lts.sel.alcatel.de (James Kanze) My experience was that you could not do robust input with scanf, and I know of no one who used it much. The general procedure in C was to read a line using fgets, and parse it by hand (using functions like strtod, and maybe even sscanf). In general, I find that input error detection in istream is far superior than that of scanf. Maybe I'm asking too much of it, however. CLAMAGE: clamage@Eng.su.com (Steve Clamage), 4 Jul 96 Considering input for predefined types, istream error detection is comparable to scanf. In fact, the current draft standard says input uses the scanf rules. Neither one is very robust for reading human-typed input, since all you get is a good/fail indication. If there is an error, you don't get very much information about what is wrong, or exactly where the error occurred. Example: int x, y, z; and the available input looks like 123 4r6 789 If you write scanf("%d%d%d", &x, &y, &z); scanf will return 2 to indicate two successful conversions. The value of z will be unchanged, x will contain 123, and y will contain 4. If you write cin >> x >> y >> z; you will find out only that not all the conversions succeeded. You can test each input individually: if( ! (cin >> x) ) // error reading x if( ! (cin >> y) ) // error reading y and get the same information as with scanf. With either istream or scanf the input is left with the 'r' unread. Istreams have a definite type-safety advantage, of course. You can't accidently store a float value into a double variable or vice-versa: double f; scanf("%f", &d); /* error: float conversion stored in double */ This error is common in C, but can't happen with istreams. For interactive input, you often want to read a line of text at a time and parse it by hand so you can give helpful error messages. Other times, all you care about is whether a given line of input is valid or not valid. In that case, code like this if( ! (cin >> x >> y >> z) ) // error in the line is adequate.