Detailed usage of c_str of

  • 2020-04-02 01:32:13
  • OfStack

Const char * c_str ();
The c_str() function returns a pointer to a normal C string, the same as this string.

C_str () converts a string object to a c compatible char * type.
In order to be compatible with c, there is no string type in c, so the string object must be converted to the string style in c through the member function c_str() of the string class object.
Note: be sure to use the strcpy() function and so on to manipulate the pointer returned by the method c_str()
For example: it's best not to:
Char * c.
String s = "1234";
C = s.c _str (); //c ends up pointing to garbage because the s object is destructed and its contents are processed

It should be used like this:
Char c [20];
String s = "1234";
Strcpy (c, s.c _str ());
So that there are no errors, c_str() returns a temporary pointer that cannot be manipulated

Here's another example
C_str () returns a string containing a string as a char*
If a function requires a char* parameter, use the c_str() method:
String s = "Hello World!" ;
Printf (" % s ", s.c _str ()); // output "Hello World!"


Related articles: