< previous page page_239 next page >

Page 239
char Arrays
A string is a series of characters. The only strings you've seen until now have been unnamed string constants used in cout statements, such as
cout << hello world.\n;
In C++, a string is an array of chars ending with a null character. You can declare and initialize a string just as you would any other array. For example:
char Greeting[] = { H, e, l, l, o,  ,
W, o, r, l, d, \0 };
The last character, \0, is the null character, which many C++ functions recognize as the terminator for a string. Although this character-by-character approach works, it is difficult to type and admits too many opportunities for error. C++ enables you to use a shorthand form of the previous line of code:
char Greeting[] = Hello World;
You should note two things about this syntax:
· Instead of single quoted characters separated by commas and surrounded by braces, you have a double-quoted string, no commas, and no braces.
· You don't need to add the null character because the compiler adds it for you.
The string Hello World is 12 bytes: Hello is 5 bytes, the space is 1, World is 5, and the null character is 1 byte.
You can also create uninitialized character arrays. As with all arrays, it is important to ensure that you don't put more into the buffer than there is room.
Listing 15.6 demonstrates the use of an uninitialized buffer.
LISTING 15.6 FILLING AN ARRAY

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    //Listing 15.6 char array buffers
 2:
 3:    #include <iostream.h>
 4:
 5:    int main()
 6:    {
 7:       char buffer[80];
 8:       cout << Enter the string: ;
 9:       cin >> buffer;
10:       cout << Here's the buffer:   << buffer << endl;
11:       return 0;
12:    }

 
< previous page page_239 next page >

If you like this book, buy it!