273 pdfsam Cplusplus Primer Plus 4th Edition

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks to b...

0 downloads 1 Views 3KB Size
This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

to be a UNIX file. 49 characters read $

End-of-File Ends Input

When a cin method detects end-of-file, recall, it sets a flag in the cin object indicating the end-of-file condition. When this flag is set, cin does not read any more input, and further calls to cin have no effect. For file input, this makes sense because you shouldn't read past the end of a file. For keyboard input, however, you might use a simulated end-of-file to terminate a loop but then want to read more input later. The cin.clear() method clears the end-of-file flag and lets input proceed again. Chapter 17, "Input, Output, and Files," discusses this further. Keep in mind, however, that in a Windows 98 console emulation mode, typing Ctrl+Z effectively terminates both input and output beyond the powers of

cin.clear() to restore them.

Common Idioms

The essential design of the input loop is this:

cin.get(ch); // attempt to read a char while (cin.fail() == false) // test for EOF { ... // do stuff cin.get(ch); // attempt to read another char } There are some shortcuts you can make. Chapter 6 introduces the ! operator, which toggles true to false, and vice versa. You can use it to rewrite the while test to look like this:

while (!cin.fail())

// while input has not failed

The return value for the cin.get(char) method is cin, an object. However, the istream class provides a function that can convert an istream object such as cin to a bool value; this conversion function is called when cin occurs in a location where a bool is expected,