C++ string c_str() Function
Example
Get a C-style string from a string, and use it with strlen():
string txt = "Hello World!";
const char* cstr = txt.c_str();
cout << cstr << "\n";
cout << strlen(cstr);
Definition and Usage
The c_str() function returns the content of a string as a C-style string: an array of char that ends with a null character (\0).
This is useful when you need a function that only works with C-style strings, like the functions in the <cstring> library. In the example, strlen() counts the characters.
The c_str function is defined in the <string> header file.
Note: You cannot change the characters through the returned pointer. The pointer only works until the string is changed.
Syntax
string.c_str();
Parameter Values
None.
Technical Details
| Returns: | A pointer (const char*) to a C-style string with the same characters as the string. |
|---|
Related Pages
Read more about strings in our String Tutorial.