#include <iostream>
using namespace std;
int main() {
string p;
p = "hello,";
// convert char* to string: simply use "="
char *m;
m = (char*)"ucas";
string q;
q = m;
/*
if we want to output a string using %s,
we should use c_str() function to convert (C++) String to (C) char*.
*/
printf("p+q = %s\n", (p + q).c_str());
// convert string to char*:
// method-1: data()
char *n;
n = p.data();
printf("n = %s\n", n);
// method-2: c_str()
char *x;
x = (char*)p.c_str();
printf("x = %s\n", x);
return 0;
}
输出:
p+q = hello,ucas
n = hello,
x = hello,
文章介绍了如何在C++中使用iostream进行字符串操作,包括将char*转换为string以及两种不同的string转回char*的方法:data()和c_str()。
6465

被折叠的 条评论
为什么被折叠?



