|
|
|
|
|
|
|
acter '\n', whichever comes first. It then appends the null character to the end of the string. With the statements |
|
|
|
|
|
|
|
|
char oneLine[81]; // Room for 80 characters plus '\0'
.
.
.
cin.get(oneLine, 81); |
|
|
|
|
|
|
|
|
the get function reads and stores an entire input line (to a maximum of 80 characters), embedded blanks and all. If the line has fewer than 80 characters, reading stops at '\n' but does not consume it. The newline character is now the first one waiting in the input stream. To read two consecutive lines worth of strings, it is necessary to consume the newline character: |
|
|
|
|
|
|
|
|
char dummy;
.
.
.
cin.get(stringl, 81);
cin.get(dummy); // Eat newline before next "get"
cin.get(string2, 81); |
|
|
|
|
|
|
|
|
The first function call reads characters up to, but not including, '\n'. If the input of dummy were omitted, then the input of string2 would read no characters because '\n' would immediately be the first character waiting in the stream. |
|
|
|
|
|
|
|
|
Finally, the ignore function-introduced in Chapter 4-can be useful in conjunction with the get function. Recall that the statement |
|
|
|
|
|
|
|
|
says to skip at most 200 input characters but stop if a newline was read. (The newline character is consumed by this function.) If a program inputs a long string from the user but only wants to retain the first four characters of the response, here is a way to do it: |
|
|
|
|
|
|
|
|
char response[5]; // Room for 4 characters plus '\0'
cin.get(response, 5); // Input at most 4 characters
cin.ignore(100, '\n'); // Skip remaining chars up to and
// including '\n' |
|
|
|
|
|
|
|
|
The value 100 in the last statement is arbitrary. Any "large enough" number will do. |
|
|
|
|
|
|
|
|
Here is a table that summarizes the differences between the >> operator and the get function when reading string data: |
|
|
|
|
|