275 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 The ...

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

The cin.get() member function with no arguments returns the next character from the input. That is, you use it in this way:

ch = cin.get(); (Recall that cin.get(ch) returns an object, not the character read.) This function works much the same as C's getchar(), returning the character code as a type int value. Similarly, you can use the cout.put() function (see Chapter 3, "Dealing with Data") to display the character:

cout.put(ch); It works much like C's putchar(), except that its argument should be type char instead of type int.

Compatibility Note Originally, the put() member had a single prototype of

put(char). You could pass it anint argument, which then would be type cast to char. The Standard also calls for a single prototype. However, many current implementations provide three prototypes: put(char), put(signed char), and put(unsigned char). Using put() with an int argument in these implementations generates an error message because there is more than one choice for converting the

int. An explicit type cast, such as cin.put(char), works for int types.

To use cin.get() successfully, you need to know how it handles the end-of-file condition. When the function reaches the end of a file, there are no more characters to be returned. Instead, cin.get() returns a special value represented by the symbolic constant EOF. This constant is defined in the iostream header file. The EOF value must be different from any valid character value so that the program won't confuse EOF with a regular character. Typically, EOF is defined as the value -1, because no character has an ASCII code of -1, but you don't need to know the actual value. Just use EOF in the program. For example, the heart of Listing 5.15 looked like this: