zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c++中string类成员函数c_str()的用法

C++ string 函数 用法 成员 Str
2023-06-13 09:15:05 时间

1.string类成员函数c_str()的原型:

constchar*c_str()const;//返回一个以null终止的c字符串

2.c_str()函数返回一个指向正规c字符串的指针,内容和string类的本身对象是一样的,通过string类的c_str()函数能够把string对象转换成c中的字符串的样式;

3.操作c_str()函数的返回值时,只能使用c字符串的操作函数,如:strcpy()等函数.因为,string对象可能在使用后被析构函数释放掉,那么你所指向的内容就具有不确定性.

eg:
char*name[20];

stringptr="tongnono";

strcpy(name,ptr.c_str());//c_str()返回的是一个临时的指针变量,不能对其操作.