The two most common ways of getting a string into an array are to initialize an array to a string constant and to read keyboard or file input into an array. Listing 4.2 demonstrates these approaches by initializing one array to a quoted string and using cin
to place an input string into a second array. The program also uses the standard C library function strlen()
to get the length of a string. The standard cstring
header file (or string.h
for older implementations) provides declarations for this and many other string-related functions.
// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring> // for the strlen() function
int main()
{
using namespace std;
const int Size = 15;
char name1[Size]; // empty array
char name2[Size] = "C++owboy"; // initialized array
// NOTE: some implementations may require the static keyword
// to initialize the array name2
cout << "Howdy! I'm " << name2;
cout << "! What's your name?
";
cin >> name1;
cout << "Well, " << name1 << ", your name has ";
cout << strlen(name1) << " letters and is stored
";
cout << "in an array of " << sizeof(name1) << " bytes.
";
cout << "Your initial is " << name1[0] << ".
";
name2[3] = ' '; // set to null character
cout << "Here are the first 3 characters of my name: ";
cout << name2 << endl;
return 0;
}
Here is a sample run of the program in Listing 4.2:
Howdy! I'm C++owboy! What's your name?
Basicman
Well, Basicman, your name has 8 letters and is stored
in an array of 15 bytes.
Your initial is B.
Here are the first 3 characters of my name: C++
What can you learn from Listing 4.2? First, note that the sizeof
operator gives the size of the entire array, 15 bytes, but the strlen()
function returns the size of the string stored in the array and not the size of the array itself. Also strlen()
counts just the visible characters and not the null character. Thus, it returns a value of 8
, not 9
, for the length of Basicman
. If cosmic
is a string, the minimum array size for holding that string is strlen(cosmic) + 1
.
Because name1
and name2
are arrays, you can use an index to access individual characters in the array. For example, the program uses name1[0]
to find the first character in that array. Also the program sets name2[3]
to the null character. That makes the string end after three characters, even though more characters remain in the array (see Figure 4.3).