Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 607

17


Getting Strings from Standard Input ..............................................................


The extraction operator (>>) can be used to fill a character array, as can the third version
of the member functions get()and the member function getline().
This form of get()takes three parameters:
get( pCharArray, StreamSize, TermChar );
The first parameter (pCharArray) is a pointer to a character array, the second parameter
(StreamSize) is the maximum number of characters to read plus one, and the third para-
meter (TermChar) is the termination character.
If you enter 20 as the second parameter,get()reads 19 characters and then null-
terminates the string, which it stores in the first parameter. The third parameter, the ter-
mination character, defaults to newline (‘\n’). If a termination character is reached
before the maximum number of characters is read, a null is written and the termination
character is left in the buffer.
Listing 17.6 illustrates the use of this form of get().

LISTING17.6 Using get()with a Character Array


0: // Listing 17.6 - Using get() with a character array
1:
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: char stringOne[256];
8: char stringTwo[256];
9:
10: cout << “Enter string one: “;
11: cin.get(stringOne,256);
12: cout << “stringOne: “ << stringOne << endl;
13:

DOuse the extraction operator (>>)
when you need to skip over whitespace.
DOuse get()with a character parameter
when you need to examine every charac-
ter, including whitespace.

DON’T stack cinstatements to get multi-
ple input if it isn’t clear what you are
doing. It is better to use multiple com-
mands that are easier to understand
than to use one long command.

DO DON’T

Free download pdf