C++ string、int 互转

本文介绍了在C++11及更高版本中,如何使用std::to_string将整型(int)转换为字符串(string),以及使用std::stoi进行反向转换。当不支持C++11时,可以利用stringstream进行类型间的转换。此外,还提到了其他相关函数如stod、stof等用于不同类型的转换。

int-> string

//C++11 支持的方法
int ntime = 800;
//tostring的参数可以是int、double、float、long等等
std::string str = std::to_string(ntime);
//""包起来相当于 const char*,不能使用 + 连接
std::string key = "5" + std::string("&&&") + str;

//不能使用C++11时
#include <sstream>
std::stringstream ss;
std::string str = "";
int ntime = 800;
ss << ntime;
ss >> str;

string -> int

//C++11 支持的方法
std::string str = "800";
int ntime = std::stoi(str);
//其他相关函数有stod、stof、stol、stold、stoll,
//返回值分别为double、float、long、long double、long long

//不能使用C++11时
#include <sstream>
std::stringstream ss;
std::string str = "800";
int ntime = 0;
ss << str;
ss >> ntime;

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值