< previous page page_671 next page >

Page 671
Thinking of a string as an abstract data type, what kinds of operations might we find useful? Here are a few:
Create and initialize a string
Input a string
Output a string
Determine the length of a string
Compare two strings
Copy one string to another
We could come up with many other operations as well, but let's look at these particular ones.
Initializing Strings
In Chapter 11, we showed how to initialize an array in its declaration, by specifying a list of initial values within braces, like this:
int delta[5] = {25, -3, 7, 13, 4};
To initialize a string variable in its declaration, you could use the same technique:
char message[8] = {'W', 'h', 'o', 'o', 'p', 's', '!', '\0'};
However, C++ allows a more convenient way to initialize a string. You can simply initialize the array by using a string constant:
char message[8] = "Whoops!";
This shorthand notation is unique to strings because there is no other kind of array for which there are aggregate constants.
We said in Chapter 11 that you can omit the size of an array when you initialize it in its declaration (in which case, the compiler determines its size). This feature is often used with strings because it keeps you from having to count the number of characters. For example,
char promptMsg[] = "Enter a positive number:";
char errMsg[] = "Value must be positive.";
Be very careful about one thing: C++ treats initialization (in a declaration) and assignment (in an assignment statement) as two distinct operations. Different rules apply. Array initialization is legal, but aggregate array assignment is not.

 
< previous page page_671 next page >