I have just started reading C++ and found c++ having rich functions for string manipulation which C does not have. I am reading these function and came across c_str()<
In C++, you define your strings as
std::string MyString;
instead of
char MyString[20];
.
While writing C++ code, you encounter some C functions which require C string as parameter.
Like below:
void IAmACFunction(int abc, float bcd, const char * cstring);
Now there is a problem. You are working with C++ and you are using std::string
string variables. But this C function is asking for a C string. How do you convert your std::string
to a standard C string?
Like this:
std::string MyString;
// ...
MyString = "Hello world!";
// ...
IAmACFunction(5, 2.45f, MyString.c_str());
This is what c_str()
is for.
Note that, for std::wstring
strings, c_str()
returns a const w_char *
.