String字符串转换为C风格字符串需要利用string类的成员函数c_str()。而C风格字符串转换转换为string字符串可以直接利用运算符=。首先介绍c_str()函数原型:
const value_type *c_str() const;
它的返回值类型为const char*,所以定义的C风格字符串需要用const char*指针指向,变量名为ch。string类型变量为str,值为hello,ch指向的字符串内容为world。代码实现如下:
#include<iostream> #include<string> using namespace std; int main() { string str="hello"; const char *ch; ch=str.c_str(); cout<<ch<<endl; ch="world"; str=ch; cout<<str<<endl; return 0; }