W3cubDocs

/C++

std::basic_string<CharT,Traits,Allocator>::c_str

const CharT* c_str() const;
(until C++11)
const CharT* c_str() const noexcept;
(since C++11)

Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.

The pointer is such that the range [c_str(); c_str() + size()] is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.

The pointer obtained from c_str() may be invalidated by:

Writing to the character array accessed through c_str() is undefined behavior.

c_str() and data() perform the same function.

(since C++11)

Parameters

(none).

Return value

Pointer to the underlying character storage.

c_str()[i] == operator[](i) for every i in [0, size()).

(until C++11)

c_str() + i == std::addressof(operator[](i)) for every i in [0, size()].

(since C++11)

Complexity

Constant.

Notes

The pointer obtained from c_str() may only be treated as a pointer to a null-terminated character string if the string object does not contain other null characters.

Example

#include <algorithm>
#include <cassert>
#include <cstring>
#include <string>
 
int main()
{
  std::string const s("Emplary");
  assert(s.size() == std::strlen(s.c_str()));
  assert(std::equal(s.begin(), s.end(), s.c_str()));
  assert(std::equal(s.c_str(), s.c_str() + s.size(), s.begin()));
  assert(0 == *(s.c_str() + s.size()));
}

See also

(C++11)
accesses the first character
(public member function)
(C++11)
accesses the last character
(public member function)
returns a pointer to the first character of a string
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/string/basic_string/c_str