数值类型和字符串之间的转换

c++11之后数值与字符串之间的转换变得更加方便。


数值转换为字符串

to_string()

函数声明在头文件<string>中。

// 头文件 <string>
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

字符串转换为浮点数


 stof( const std::string& str, std::size_t* pos = 0 );//float    
 stod( const std::string& str, std::size_t* pos = 0 );//double   
 stold( const std::string& str, std::size_t* pos = 0 );//long double

字符串转换为整数

 stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );//int 
 stol( const std::string& str, std::size_t* pos = 0, int base = 10 );//long 
 stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );//long long
 stoul( const std::string& str, std::size_t* pos = 0, int base = 10 );//unsigned long  
 stoull( const std::string& str, std::size_t* pos = 0, int base = 10 );//unsigned long long

str:要转换的字符串
pos:传出参数, 记录从哪个字符开始无法继续进行解析, 比如: 123abc, 传出的位置为3
base:若 base 为 0 ,则自动检测数值进制:若前缀为 0 ,则为八进制,若前缀为 0x 或 0X,则为十六进制,否则为十进制。
除第一个参数外,其余默认即可。

参考

https://subingwen.cn/cpp/convert/#2-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值