Managing Arrays and Strings 433
13
functions recognize as the terminator for a C-style 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. It is
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 C-style string, no commas, and no braces. - You don’t need to add the null character because the compiler adds it for you.
When you declare a string, you need to ensure that you make it as large as you will need.
The length of a C-style string includes the number of characters including the null char-
acter. For example, Hello World is 12 bytes. Hello is 5 bytes, the space is 1 byte, World
is 5 bytes, 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 it than there is room for. Listing 13.10 demonstrates
the use of an uninitialized buffer.
LISTING13.10 Filling an Array
0: //Listing 13.10 char array buffers
1:
2: #include <iostream>
3:
4: int main()
5: {
6: char buffer[80];
7: std::cout << “Enter the string: “;
8: std::cin >> buffer;
9: std::cout << “Here’s the buffer: “ << buffer << std::endl;
10: return 0;
11: }
Enter the string: Hello World
Here’s the buffer: Hello
On line 6, a character array is created to act as a buffer to hold 80 characters.
This is large enough to hold a 79-character C-style string and a terminating null
character.
On line 7, the user is prompted to enter a C-style string, which is entered into the buffer
on line 8. cinwrites a terminating null to the buffer after it writes the string.
OUTPUT
ANALYSIS