C风格的字符串很容易转化成C++风格的字符串,反过来却可能引起语法错误。
要注意用字符数组表示c风格字符串的时候,最后一位必须是 '\0' 这也是为什么设置网络编程的时候,缓存区char buf[MAX] ,要用memset(buf,‘\0’,MAX) ,而read(fd,buf,MAX-1)。(printf和cout 也只能正常输出 \0结尾的字符数组,否则不知道到哪停止。)
一、C风格的字符串转化为C++的string对象(注意必须以\0结尾)
C++中,string 类能够自动将C 风格的字符串转换成string 对象
int main() {
//C风格字符串定义方法
char *c1 = "hello,world";
char c2[] = "hello,world";
//c风格字符串能直接给string 赋值
string s1 = c1;
cout << c1 << '\n'
<< c2 << '\n'
<< s1 << '\n';
cout << endl;
system("pause");
}
二、C++的string对象转化为C风格的字符串
要实现这种转化,需调用string类的c_str()方法
#include <IOSTREAM>
#include <STRING>
using namespace std;
int main(){
string str2("hello, world!");
char *str = str2.c_str();
cout << "C++风格:" << str2 <<endl;
cout << "C风格:" << str <<endl;
return 0;
}
结果报错:cannot convert from 'const char *' to 'char *'
查看一下c_str()的源代码:const _E *c_str() const {return (_Ptr == 0 ? _Nullstr() : _Ptr); }
再查看_E:typedef char _E
这下全明白了。c_str()返回的是const char *类型。在第7行str的声明前加上限定符const,一切就正常了。