Namespaces
Variants

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

来自cppreference.net
 
 
 
std::basic_string
 
const CharT* c_str() const;
(C++11 起为 noexcept)
(C++20 起为 constexpr)

返回指向空终止字符数组的指针,该数组中的数据与字符串中存储的数据等效。

指针满足区间 [c_str(), c_str() + size()] 有效且其中的值对应于字符串中存储的值,并在最后一个位置之后附加一个空字符。

从 c_str() 获取的指针可能因以下操作而失效:

  • 向任何标准库函数传递字符串的非 const 引用,或
  • 调用字符串的非 const 成员函数,但 operator[][] 、at()、front()、back()、begin()、rbegin()、end() 和 rend()(C++11 起) 除外。

通过 c_str() 访问的字符数组进行写操作是未定义行为。

c_str() 和 data() 执行相同的函数。

(C++11 起)

参数

(无)

返回值

指向底层字符存储的指针。

c_str ( ) [ i ] == operator [ ] ( i ) 对于每个在 [ ​ 0 ​ , size ( ) ) 范围内的 i 成立。

(C++11 前)

c_str ( ) + i == std:: addressof ( operator [ ] ( i ) ) 对于每个在 [ ​ 0 ​ , size ( ) ] 范围内的 i 成立。

(C++11 起)

复杂度

常量。

注释

从 c_str() 获取的指针仅当字符串对象不包含其他空字符时,才能被视为指向以空字符结尾的字符串的指针。

示例

#include <algorithm>
#include <cassert>
#include <cstring>
#include <string>
extern "C" void c_func(const char* c_str)
{
    printf("c_func called with '%s'\n", c_str);
}
int main()
{
    std::string const s("Emplary");
    const char* p = s.c_str();
    assert(s.size() == std::strlen(p));
    assert(std::equal(s.begin(), s.end(), p));
    assert(std::equal(p, p + s.size(), s.begin()));
    assert('\0' == *(p + s.size()));
    c_func(s.c_str());
}

输出:

c_func called with 'Emplary'

参见

( DR* )
访问首字符
(公开成员函数)
( DR* )
访问末字符
(公开成员函数)
返回指向字符串首字符的指针
(公开成员函数)