string与其他数据类型之间的转换

1.string to others

C++封装了一系列函数,使得string类型的数据能够被方便地转换到其他数据类型。

这些函数名有着统一的风格,即stox(string to x,x为要转换到的类型名缩写)。

函数名转换到
stoiint
stollong
stoulunsigned long
stolllong long
stoullunsigned long long
stoffloat
stoddouble
stoldlong double
1 string s;
2 s = "1989";
3 int num = stoi(s);
4 long long nums = stol(s);
5 cout << num + 30 << endl;
6 cout << nums + 2147481659 << endl;//比int的最大值大1

运行结果:

 

2.others to string

从其他类型转换到string只要记住一个函数即可。

涉及到宽字符时有所变化。

函数名转换为
to_stringstring
to_wstringwstring

示例:

1 string s;
2 wstring ss;
3 int num = 1989;
4 long long max_sz = ss.max_size();
5 s = to_string(num);
6 cout << s[0] << s[1] << s[2] << s[3] << endl;
7 cout << max_sz << endl;
8 //实在找不到这么长的演示...

运行结果:

 

以后遇到麻烦的字符串和大数终于可以轻松一点了。

转载于:https://www.cnblogs.com/CofJus/p/10588629.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值