|
|
|
|
|
|
|
char myStr[20] = "Hello"; // OK
.
.
.
myStr = "Howdy" // Not allowed |
|
|
|
|
|
|
|
|
In Chapter 11, we emphasized that C++ does not provide aggregate operations on arrays. There is no aggregate assignment, aggregate comparison, or aggregate arithmetic on arrays. We also said that aggregate input/output of arrays is not possible, with one exception. Strings are that exception. Let's look first at output. |
|
|
|
|
|
|
|
|
To output the contents of an array that is not a string, you aren't allowed to do this: |
|
|
|
|
|
|
|
|
int alpha [100];
.
.
.
cout << alpha; // No |
|
|
|
|
|
|
|
|
Instead, you must write a loop and print the array elements one at a time. However, aggregate output of a null-terminated char array (that is, a string) is valid. The string can be a string constant (as we've been doing since Chapter 2): |
|
|
|
|
|
|
|
|
or it can be a string variable: |
|
|
|
|
|
|
|
|
char msg[8] = "Welcome";
.
.
.
cout << msg; |
|
|
|
|
|
|
|
|
In both cases, the insertion operator (<<) outputs each character in the array until the null character is found. It is up to you to double-check that the terminating null character is present in the array. If not, the << operator will march through the array and into the rest of memory, printing out bytes until-just by chance-it encounters a byte whose integer value is 0. |
|
|
|
|
|
|
|
|
To input strings, we have several options in C++. The first is to use the extraction operator (>>). When reading input characters into a string variable, the >> operator skips any leading whitespace characters such as blanks and newlines. It then reads successive characters into the array, stopping at the first trailing whitespace character (which is not consumed, but remains as |
|
|
|
|
|