我是靠谱客的博主 稳重帽子,这篇文章主要介绍C风格字符串和C++string对象的相互转化,现在分享给大家,希望可以做个参考。

C风格的字符串很容易转化成C++风格的字符串,反过来却可能引起语法错误。

要注意用字符数组表示c风格字符串的时候,最后一位必须是 '' 这也是为什么设置网络编程的时候,缓存区char buf[MAX] ,要用memset(buf,‘’,MAX) ,而read(fd,buf,MAX-1)。(printf和cout 也只能正常输出 结尾的字符数组,否则不知道到哪停止。)
一、C风格的字符串转化为C++的string对象(注意必须以结尾)
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,一切就正常了。
 

最后

以上就是稳重帽子最近收集整理的关于C风格字符串和C++string对象的相互转化的全部内容,更多相关C风格字符串和C++string对象内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部