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??
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.
std::string::c_strReturns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
C++ String Library - c_str.
The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated. Note that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.
c_str
returns a const char*
that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string
to a function that expects to work with a C-style string.
For example, consider this code:
std::string string("Hello world!"); std::size_t pos1 = string.find_first_of('w'); std::size_t pos2 = static_cast<std::size_t>(std::strchr(string.c_str(), 'w') - string.c_str()); if (pos1 == pos2) { std::printf("Both ways give the same result.\n"); }
See it in action.
Notes:
¹ This is not entirely true because an std::string
(unlike a C string) can contain the \0
character. If it does, the code that receives the return value of c_str()
will be fooled into thinking that the string is shorter than it really is, since it will interpret \0
as the end of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With