std::string 与 char* 之间的转换
std::string 是c++标准库里面其中一个,封装了对字符串的操作
一、把string转换为char*有三种方法:
1. .data
2. .c_str
3. .copy
using namesapce std; string str = "hello world"; const char *p = str.data(); printf(p); //==> // hello world
string str = "hello world"; const char *p = str.c_str(); printf(p); //==> // hello world
string str = "hello world"; char p[40]; str.copy(p, 5, 0);//这里5,代表复制几个字符,0代表复制的位置 *(p + 5) = '\0';//要手动加上结束符 printf(p); //==> // hello
2:把char*转换为string的方法
const char* p = "Hello world"; std::string str = p; // 可以对str直接赋值 cout << str; //==> // hello world
注:
当定义一个string类型的变量后,使用printf_s会出现问题。
std::string str = "Hello world";
printf_s("%s", str);
//==>
// 乱码
这样的输出是有问题的,因为%s要求的是后面对象的首地址。但是string不是这样的类型,所以会出错。使用
cout << str << endl; //这样输出是没有问题的。 //==> // hello world
或者
printf_s("%s", str.c_str());
//==>
// hello world
原文链接:https://blog.csdn.net/u014801811/article/details/80113382