Topic: Mixing formatted and unformatted I/O


Author: notbob@tessellation.com (Robert Allan Schwartz)
Date: 1998/04/07
Raw View
When I mix formatted and unformatted I/O, as in:

char buffer[128];
cin.getline(buffer, sizeof(buffer));
int i;
cin >> i;

I notice that I get strange behavior. The program doesn't wait for the
second input, and charges merrily along. This also depends on the compiler.

What does the standard say about this?

Thanks,

Robert

-----------------------------------------------------------------------
Robert Allan Schwartz       | voice (617) 499-9470  | Freelance instructor
955 Massachusetts Ave. #354 | fax   (617) 868-8209  | of C, C++, OOAD, OODB,
PO Box 9183                 |                       | and Java
Cambridge, MA 02139         | email notbob@tessellation.com

URL   http://www.tessellation.com/index.html
-----------------------------------------------------------------------
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1998/04/08
Raw View
In article B1500B999668172AE4@p10.tc5.metro.ma.tiac.com, notbob@tessellation.com (Robert Allan Schwartz) writes:
>When I mix formatted and unformatted I/O, as in:
>
>char buffer[128];
>cin.getline(buffer, sizeof(buffer));
>int i;
>cin >> i;
>
>I notice that I get strange behavior. The program doesn't wait for the
>second input, and charges merrily along. This also depends on the compiler.

If you run into an error, cin would be put into an error state, and the
"cin>>i" would not extract any input. Except for such a situation, the
code should work by extracting a complete line into "buffer", discard
the newline, then extract characters into i.

Possible errors include not finding a newline before filling "buffer",
and finding an initial non-numeric character when attempting "cin>>i".
If whitespace skipping is off and there is whitespace between the first
newline and the first numeric character, that would be an error.

Beyond this exact example, mixing formatted and unformatted I/O can
cause line synchronization problems. The sequence that usually causes
problems is something like
 cin >> i;
 getline(buffer, sizeof(buffer));
The first statement leaves the trailing newline in the input, and
the getline just gets whatever is left on the first line, which might
be nothing.

---
Steve Clamage, stephen.clamage@sun.com
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]