c_str function

Syntax: 
const char *c_str(); The 
c_str() function returns a pointer constant to a regular C string, the content is the same as this string string. 
This is for compatibility with the C language, there is no string type in the C language, so it must be passed The member function c_str() of the string class object converts the string object into a string style in c. 
NOTE: Be sure to use strcpy () function, etc. The method of operation of the c_str () returns a pointer 
such as: best not: 
char * C; 
String S = "1234"; 
C = s.c_str (); // to point C and finally The content of is garbage, because the s object is destroyed and its content is processed. At the same time, the compiler will report an error-assigning a const char * to a char *. 

It should be used like this: 
char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 
so that there will be no error, c_str() returns a temporary pointer, which cannot be operated 

on For example, 
c_str() returns a string containing a string in the form of char*. 
If a function requires a char* parameter, you can use the c_str() method: 
string s = "Hello World!"; 
printf("%s", s. c_str()); //Output "Hello World!"

Guess you like

Origin blog.csdn.net/nyist_yangguang/article/details/114576510