Key points: printf can only output the built-in data of C language, but string is not built-in, it is just an extended class, and it is definitely wrong to output directly!
In fact, the method is very simple, just use the following function to output it:
string test = "测试代码段";
printf("%s",test.c_str());
Call the c_str() function to output, and use cout to output.
Here are a few notes about the c_str() function:
1. The c_str() function returns a pointer to a regular c string, the content of which is the same as the object of the string class itself, and the string object can be converted into the style of a string in c through the c_str() function of the string class;
2.
The c_str() function returns a pointer to a regular c string, the content of which is the same as this string.
This is for compatibility with the C language. There is no string type in the C language, so the string object must be converted into a string style in C through the member function c_str() of the string class object.
Note: Be sure to use the strcpy() function, etc. to manipulate the pointer returned by the method c_str()
For example: it is better not to:
char* p;
string test="test";
p = test.c_str(); //c最后指向的内容是废用,因为s对象被析构,其内容被处理
It should be used like this:
char p[20];
string test="test";
strcpy(p,test.c_str());
In this way, c_str() returns a temporary pointer and cannot be manipulated.