|
|
|
|
|
|
|
the first character waiting in the input stream). The >> operator also takes care of adding the null character to the end of the string. For example, assume we have the following code: |
|
|
|
|
|
|
|
|
char firstName[31]; // Room for 30 characters plus '\0'
char lastName[31];
cin >> firstName >> lastName; |
|
|
|
|
|
|
|
|
Suppose that the input stream initially looks like this (where denotes a blank): |
|
|
|
|
|
|
|
|
Then our input statement stores 'M', 'a', 'r', 'y', and '\0' into firstName[0] through firstName [4]; stores 'S', 'm', 'i', 't', 'h', and '\0' into lastName [0] through lastName [5]; and leaves the input stream as |
|
|
|
|
|
|
|
|
Although the >> operator is widely used for string input, it has two potential drawbacks. |
|
|
|
|
|
|
|
|
1. If your string variable isn't large enough to hold the sequence of input characters (and the '\0'), the >> operator will continue to store characters into memory past the end of the array. |
|
|
|
|
|
|
|
|
2. The >> operator cannot be used to input a string that has blanks within it. (It stops reading as soon as it encounters the first whitespace character.) |
|
|
|
|
|
|
|
|
To deal with these facts, we use a variation of the get function. We have used the get function to input a single character, even if it is a whitespace character: |
|
|
|
|
|
|
|
|
The get function also can be used to input string data, in which case the function call requires two parameters. The first is a string variable and the second is an int expression. |
|
|
|
|
|
|
|
|
cin.get(myStr, charCount + 1); |
|
|
|
|
|
|
|
|
The get function does not skip leading whitespace characters and continues until it either has read charCount characters or it reaches the newline char- |
|
|
|
|
|