版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89761524
一 点睛
C++提供的由C++字符串转换成对应的C字符串的方法是使用data()、c_str()和copy()来实现。
data():以字符数组的形式返回字符串的内容,但并不添加'\0'
c_str():返回一个以'\0'结尾的字符数组
copy():把字符串的内容复制或写入既有的c_string或字符数组内。
注意:C++字符串并不以'\0'结尾。
c_str()语句可以生产一个const char *指针,并指向字符数组。这个数字的数据是临时的,当有一个改变这些数据的成员函数被调用,其中的数据就会失效。因此,要么现用现转换,要么把它的数据复制到用户自己可以管理的内存后再转换。
二 c_str()使用方法实战
1 代码
#include<iostream>
#include<string>
using namespace std;
int main(){
string str="Hello world.";
const char * cstr=str.c_str();
cout<<cstr<<endl;
str="Abcd.";
cout<<cstr<<endl;
return 0;
}
2 运行
[root@localhost charpter03]# g++ 0303.cpp -o 0303
[root@localhost charpter03]# ./0303
Hello world.
Abcd.
3 说明
改变了str的内容,cstr的内容也会随着改变。所以如果上面继续使用C指针的话,导致的错误将是不可想象的。既然C指针指向的内容容易失效,就可以考虑把数据复制出来。
三 将c_str()里的内容负责出来以保持有效性
1 代码
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main(){
char * cstr=new char[20];
string str="Hello world.";
strncpy(cstr,str.c_str(),str.size());
cout<<cstr<<endl;
str="Abcd.";
cout<<cstr<<endl;
return 0;
}
2 运行
[root@localhost charpter03]# g++ 0304.cpp -o 0304
[root@localhost charpter03]# ./0304
Hello world.
Hello world.
3 说明
用strncpy函数将str.c_str()内容复制到cstr里了,这样就能保证cstr里的内容不随str内容改变而改变。