Two problems occur with the program in Listing 13.10. First, if the user enters more than
79 characters,cinwrites past the end of the buffer. Second, if the user enters a space,
cinthinks 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 cincalled get(). cin.get()
takes three parameters:
- The buffer to fill
- The maximum number of characters to get
- The delimiter that terminates input
The delimiter defaults to a newline character. Listing 13.11 illustrates the use of get().
LISTING13.11 Filling an Array With a Maximum Number of Characters.
0: //Listing 13.11 using cin.get()
1:
2: #include <iostream>
3: using namespace std;
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: }
Enter the string: Hello World
Here’s the buffer: Hello World
Line 9 calls the method get()of cin. The buffer declared on 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 no greater than 79 to allow for the terminating null. No
need exists to provide a terminating character because the default value of newline is suf-
ficient.
If you enter spaces, tabs, or other whitespace characters, they are assigned to the string.
A newline character ends the input. Entering 79 characters also results in the end of the
input. You can verify this by rerunning the listing and trying to enter a string longer than
79 characters.
OUTPUT
434 Day 13
ANALYSIS