关于c_str( )

原文地址:关于c_str( )作者:Jae_Joong
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

#include

#include

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.
原文链接: https://www.cnblogs.com/gamesky/archive/2012/09/13/2683502.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/62717

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午10:32
下一篇 2023年2月9日 上午10:32

相关推荐