to_string函数(将数字转换成字符串)
一般常用的转换字符串的方法std::stringstream,但是效率较低;目前C ++11提供了std::to_string
效率方面:C风格的sprintf()没有动态分配内存效率最高;std::to_string其次;std::stringstream效率最差
从C++17开始,std::to_string的效率将不差于sprintf,同时有类型更安全的转换函数std::to_char。
函数重载原型:
l w string to_string(int val);
l w string to_string(long val);
l w string to_string(long long val);
l w string to_string(unsigned val);
l w string to_string(unsigned long val);
l w string to_string(unsigned long long val);
l w string to_string(float val);
l w string to_string(double val);
l w string to_string(long double val);
.#include <iostream>
.#include <string> // std::to_string
.#include <sstream> // std::stringstream
.int main()
.{
. // old method
. std::stringstream ss;
. ss << 1.23;
. std::string str = ss.str();
. std::cout << str << std::endl;
. // new method
. std::string pi = "pi is" + std::to_string(3.1415926);
. std::string perfect = std::to_string( + + + + ) + "is a perfect number";
. std::cout << pi << std::endl;
. std::cout << perfect << std::endl;
. return ;
.}
1. #include <iostream>
2. #include <string> // std::to_string
3. #include <sstream> // std::stringstream
4. int main()
5. {
6. // old method
7. std::stringstream ss;
8. ss << 1.23;
9. std::string str = ss.str();
10. std::cout << str << std::endl;
11. // new method
12. std::string pi = "pi is" + std::to_string(3.1415926);
13. std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + "is a perfect number";
14. std::cout << pi << std::endl;
15. std::cout << perfect << std::endl;
16. return 0;
17. }
最新文章
- 和我一起看API(一)你所不知道的LinearLayout补充
- php中include()和require()的区别
- servlet乱码问题总结
- Codeforces Beta Round #17 C. Balance DP
- 2015年目标一:学习掌握python
- 跨平台轻量级redis、ssdb代理服务器(C++ 11编写)
- PHP中大括号{}用法总结
- 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
- linux中安装easy_install(setuptools)
- SMTP 553
- Android线程之Thread 、Runnable 的两个例子
- jquery.vilidate的运用
- 适配ios11与iphone x实践
- centOS 搭建pipelineDB docs
- hdu 1880 魔咒字典
- 新手学习WEB前端流程以及学习中常见的误区
- NodeJS Addon 多线程通信
- Emacs 中使用 shell
- pycharm设置pytest运行程序
- webpack打包之有依赖es2015模块