Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of c_str function In c++

Tags:

c++

c

string

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??

like image 459
Amit Singh Tomar Avatar asked Sep 14 '11 12:09

Amit Singh Tomar


People also ask

Where is c_str defined?

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.

What is the purpose of the c_str () member function of std :: string?

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.

What library is c_str in?

C++ String Library - c_str.

What type does c_str return?

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.


1 Answers

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.

like image 195
Jon Avatar answered Oct 17 '22 19:10

Jon