basic_string::c_str

const charT* c_str() const;
const charT* c_str() const noexcept;
獲取 C 字串等效項
返回指向一個數組的指標,該陣列包含一個以 null 結尾的字元序列(即 C 字串),表示 basic_string 物件的當前值。

該陣列包括構成 basic_string 物件值的相同字元序列,外加一個附加的終止空字元(charT()) 在末尾。

程式不得更改此序列中的任何字元。
返回的指標指向 basic_string 物件當前用於儲存字元的內部陣列,這些字元符合其值。

basic_string::databasic_string::c_str都是同義詞並返回相同的值。

返回的指標可能會因進一步呼叫修改物件的其他成員函式而失效。

引數



返回值

指向 basic_string 物件值的 C 字串表示形式的指標。

charTbasic_string 的字元型別(即,它的第一個模板引數)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>

int main ()
{
  std::string str ("Please split this sentence into tokens");

  char * cstr = new char [str.length()+1];
  std::strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  char * p = std::strtok (cstr," ");
  while (p!=0)
  {
    std::cout << p << '\n';
    p = strtok(NULL," ");
  }

  delete[] cstr;
  return 0;
}

輸出
Please
split
this
sentence
into
tokens


複雜性、迭代器、訪問、異常

未指定或矛盾的規範。

複雜度

常量。

迭代器有效性

沒有變化。

資料競爭

該物件被訪問。

異常安全

無異常保證:此成員函式從不丟擲異常。

另見