< previous page page_240 next page >

Page 240
Output:
Enter the string: Hello World
Here's the buffer: Hello
Analysis: On line 7 a buffer is declared to hold 80 characters. This is large enough to hold a 79-character string and a terminating null character.
On line 8 the user is prompted to enter a string, which is entered into the buffer on line 9. It is the syntax of cin to write a terminating null to the buffer after it writes the string.
There are two problems with the program in Listing 15.6. First, if the user enters more than 79 characters, cin writes past the end of the buffer. Second, if the user enters a space, cin thinks that it is the end of the string, and it stops writing to the buffer.
To solve these problems, you must call a special method on cin:get(). Cin.get() takes three parameters:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
The buffer to fill
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
The maximum number of characters to get
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
The delimiter that terminates input
The default delimiter is newline. Listing 15.7 illustrates its use.
LISTING 15.7 FILLING AN ARRAY

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    //Listing 15.7 using cin.get()
 2:
 3:    #include <iostream.h>
 4:
 5:    int main()
 6:    {
 7:       char buffer[80];
 8:       cout << Enter the string: ;
 9:       cin.get(buffer, 79);       // get up to 79 or newline
10:       cout << Here's the buffer:  << buffer << endl;
11:       return 0;
12:    }

Output:
Enter the string: Hello World
Here's the buffer: Hello World
Analysis: Line 9 calls the method get() of cin. The buffer declared in line 7 is passed in as the first argument. The second argument is the maximum number of characters to get. In this case, it must be 79 to allow for the terminating null. There is no need to provide a terminating character because the default value of newline is sufficient.
cin and all its variations are covered in Hour 21, The Preprocessor. In that hour, streams are discussed in depth.

 
< previous page page_240 next page >

If you like this book, buy it!