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()
and from what I understand is c_str
convert a string which may be null terminated or may not be to a null terminated string .Is it true?
Can anyone suggest me some example so that i can understand the use of c_str function??
In C/C++ programming there are two types of strings: the C strings and the standard strings. With the <string>
header, we can use the standard strings. On the other hand, the C strings are just an array of normal chars. So, in order to convert a standard string to a C string, we use the c_str()
function.
for example
// a string to a C-style string conversion//
const char *cstr1 = str1.c_str();
cout<<"Operation: *cstr1 = str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"\nOperation: strlen(cstr1)"<<endl;
cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;
And the output will be,
Operation: *cstr1 = str1.c_str()
The C-style string c_str1 is: Testing the c_str
Operation: strlen(cstr1)
The length of C-style string str1 = 17
Most OLD c++ and c functions, when deal with strings, use const char*
.
With STL and std::string
, string.c_str()
is introduced to be able to convert from std::string
to const char*
.
That means that if you promise not to change the buffer, you'll be able to use read only string contents. PROMISE = const char*
Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.
Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is
float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);
This is pretty common use I suppose.
It's used to make std::string
interoperable with C code that requires a null terminated char*
.
c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).
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 *
.
Source: Stackoverflow.com