标准 C++ 类别的成员函式 c_str()

功能:将string物件转换成C语言形式的字串常数。

使用格式:const char* c_str ( ) const;

[adsense][/adsense]

说明:c_str() 演算法会把string物件转换成C语言形式的字串常数。由于转换之后的字串已经变成常数,因此无法再任意更改。若有特殊原因必须更改字串常数时,应该先把字串常数储存到缓冲区(buffer)之后再予以更改。

范例:

// strings and c-strings #include <iostream> #include <cstring> #include <string> using namespace std; int main () { char * cstr, *p; string str ("Please split this phrase into tokens"); cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str p=strtok (cstr," "); while (p!=NULL) { cout << p << endl; p=strtok(NULL," "); } delete[] cstr; return 0; }

 

ㄚ琪在Windows的命令列下,用g++编译,输出:

Please
split
this
phrase
into
tokens