【C++】string、char*互相转换

string 2 char*

c_str()方法返回一个const char* 类型的指针变量,使用strcpy函数copy

string str = "abcs";
char* chs = new char[str.length()+1];
strcpy(chs, str.c_str());
cout << chs << endl;

(const) char* 2 string

const char 或 char 转换为string

char chs[] = "char str";
const char* cchs = "const char str";
string s = cchs;
string cs = chs;
cout << s << " " << cs << endl;

输出

const char str char str

你可能感兴趣的:(C++)