std::string 与 char* 之间的转换

std::string 是c++标准库里面其中一个,封装了对字符串的操作

1:把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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值