1 //char数组和string的转换 2 #include<iostream> 3 using namespace std; 4 int main() 5 { 6 char ch[]="hello world"; 7 // string s=ch;/* string可以直接用char数组赋值*/ 8 string s(ch);/* 对string赋值char数组差不多就这两种*/ 9 cout<<"ch="<<ch<<endl; 10 printf("ch=%s\n",ch); 11 cout<<"s="<<s<<endl;/*printf("s=%s",s); string不能直接用printf输出,需要用.c_str()*/ 12 printf("s=%s\n",s.c_str()); 13 string a="helloworldaaa"; 14 const char *c; 15 c=a.c_str(); 16 cout<<"c="<<c<<endl; 17 c=s.c_str(); 18 cout<<"c="<<c<<endl;/* 对const char* 数组赋值,可以用string.c_str()*/ 19 }
一切尽在注释中。
原文:https://www.cnblogs.com/dayq/p/12181961.html