C++ String 库 - c_str
描述
它返回一个指向数组的指针,该数组包含一个以 null 结尾的字符序列(即 C 字符串),表示字符串对象的当前值。
声明
以下是 std::string::c_str 的声明。
const char* c_str() const;
C++11
const char* c_str() const noexcept;
C++14
const char* c_str() const noexcept;
参数
none
返回值
它返回一个指向数组的指针,该数组包含一个以 null 结尾的字符序列(即 C 字符串),表示字符串对象的当前值。
异常
如果抛出异常,则字符串没有变化。
示例
在下面的 std::string::c_str 示例中。
#include <iostream>
#include <cstring>
#include <string>
int main () {
std::string str ("Please divide this sentance into parts");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
char * p = std::strtok (cstr," ");
while (p!=0) {
std::cout << p << '\n';
p = std::strtok(NULL," ");
}
delete[] cstr;
return 0;
}
示例输出应该是这样的 −
Please divide this sentance into parts

