c_str() 是c++ 中 string類 (class) 的 函數,它能把 string類 的對象里的字符串 轉換成 C 中 char 型變量的字符串。c_str()返回了一個指向常量數組的指針,例如:
string s1 = "hello";
const char* str = s1.c_str();
由于c_str函數的返回值是const char* 的,若想直接賦值給char*,就需要我們進行相應的操作轉化,下面是這一轉化過程。需要注意的是,操作c_str()函數的返回值時,只能使用c字符串的操作函數,如:strcpy()等函數.因為,string對象可能在使用后被析構函數釋放掉,那么你所指向的內容就具有不確定性.
#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()); //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;
}
輸出:
Please
split
this
phrase
into
tokens.