Class string provides member functions for converting string class objects to C-style pointer-based strings. As mentioned earlier, unlike pointer-based strings, strings are not necessarily null terminated. These conversion functions are useful when a given function takes a pointer-based string as an argument. Figure 18.9 demonstrates conversion of strings to pointer-based strings.
Figure 18.9. Converting strings to C-style strings and character arrays.
(This item is displayed on page 900 in the print version)
1 // Fig. 18.9: Fig18_09.cpp
2 // Converting to C-style strings.
3 #include
4 using std::cout;
5 using std::endl;
6
7 #include
8 using std::string;
9
10 int main()
11 {
12 string string1( "STRINGS" ); // string constructor with char* arg
13 const char *ptr1 = 0; // initialize *ptr1
14 int length = string1.length();
15 char *ptr2 = new char[ length + 1 ]; // including null
16
17 // copy characters from string1 into allocated memory
18 string1.copy( ptr2, length, 0 ); // copy string1 to ptr2 char*
19 ptr2[ length ] = ' |