一般常用的转换字符串的方法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. }

最新文章

  1. 和我一起看API(一)你所不知道的LinearLayout补充
  2. php中include()和require()的区别
  3. servlet乱码问题总结
  4. Codeforces Beta Round #17 C. Balance DP
  5. 2015年目标一:学习掌握python
  6. 跨平台轻量级redis、ssdb代理服务器(C++ 11编写)
  7. PHP中大括号{}用法总结
  8. 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
  9. linux中安装easy_install(setuptools)
  10. SMTP 553
  11. Android线程之Thread 、Runnable 的两个例子
  12. jquery.vilidate的运用
  13. 适配ios11与iphone x实践
  14. centOS 搭建pipelineDB docs
  15. hdu 1880 魔咒字典
  16. 新手学习WEB前端流程以及学习中常见的误区
  17. NodeJS Addon 多线程通信
  18. Emacs 中使用 shell
  19. pycharm设置pytest运行程序
  20. webpack打包之有依赖es2015模块

热门文章

  1. python爬虫简单架构原理及示例
  2. 取得Linux系统的各种统计信息
  3. 【JavaScript框架封装】实现一个类似于JQuery的DOM框架的封装
  4. Problem 9
  5. mybatis入门截图总结
  6. jQuery练习总结(二)
  7. sw算法求最小割学习
  8. nodejs-Sream
  9. 洛谷—— P1803 凌乱的yyy
  10. 今天我也用上了阿里云的Centos