In C++ a string can be implemented as an array of characters. When declaring
an array of char to hold string, an extra char must be includes to include the
string terminator: '\0'.
An array can be declared and given an initial value as shown below:
char company[] = "Widgets Inc."; //company
is char [13]
In this example the array is given a dimension of the exact size for the initial string: 13 to allow a char for '\0'. When the string is printed, only the characters before the \0 are printed.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| W | i | d | g | e | t | s | I | n | c | . | \0 |
The program shown below reads in a name:
| Run this program program several times. Try each of the following:
Enter your name: Sam Hello, Sam! //Great! It works!. Enter your name: Robin Banks Hello, Robin! //cin stops when it reads a space. Enter your name: Robert Banks ERROR ERROR //an array of 12 characters can only have 11 letters. |
If we would like to read in names as first space last (Robin Banks for example), the following program can be used:
The program shown below reads in a name:
| Run this program program several times. Try each of the following:
Enter your name: Sam Hello, Sam! //Great! It works!. Enter your name: Robin Banks Hello, Robin Banks! //cin stops when it reads a space. Enter your name: George Washington Hello, George Wash! |
Notice that the last example read only the first 11 characters that were input.
(The rest are still in the input buffer waiting for the next read. This will
create another problem tha the programmer must deal with! At least it didn't
crash!)
All of the computer_science activities with description in Arabic, 汉语, English, Français, Deutsch, Indonesian, Italiano, 日本語, Portuguêes, Русский, Español,