The string class of the Standard Library provides three member functions to get the c-type character arrays from a string: c_str (), data (), copy (p, n ).
1. c_str (): generate a const char * pointer pointing to an array terminated with null characters.
Note:
① The data in this array is temporary. When a member function that changes the data is called, the data in the function becomes invalid. Therefore, you can either convert the data first or copy the data to the memory that you can manage. Note.See the following example:
constchar* c;string s="1234";c = s.c_str(); cout<<c<<endl;
// Output: 1234s="abcd";cout<<c<<endl;
// Output: abcd |
If we continue to use the c pointer above, the errors will be unimaginable. For example, 1234 is changed to abcd.
In fact, the above c = s. c_str (); is not a good habit. Since the content pointed to by the c pointer is easy to expire, we should follow the above method. How can we copy the data? This requires strcpy and other functions (recommended ).
//const char* c; //①//char* c; //②//char c[20]; char* c=newchar;string s="1234";//c = s.c_str(); strcpy(c,s.c_str());cout<<c<<endl;
// Output: 1234s="abcd";cout<<c<<endl;
// Output: 1234 |
Note: You can no longer write the const value to the const as shown in ① above; nor can you use the uninitialized local variable "c" as shown in ② ", an error occurs.
② C_str () returns a pointer to the character array that the client program can read and cannot modify. You do not need to manually release or delete this pointer.