zoukankan      html  css  js  c++  java
  • 函数————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);

     1 1.#include <iostream>  
     2 2.#include <string// std::to_string  
     3 3.#include <sstream> // std::stringstream  
     4 4.int main()  
     5 5.{  
     6 6.    // old method  
     7 7.    std::stringstream ss;  
     8 8.    ss << 1.23;  
     9 9.    std::string str = ss.str();  
    10 10.    std::cout << str << std::endl;  
    11 11.    // new method  
    12 12.    std::string pi = "pi is" + std::to_string(3.1415926);  
    13 13.    std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + "is a perfect number";  
    14 14.    std::cout << pi << std::endl;  
    15 15.    std::cout << perfect << std::endl;  
    16 16.    return 0;  
    17 17.}  

    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. }  

  • 相关阅读:
    看《你必须知道的.NET》有感工厂模式的另类解读
    学习笔记:PDO
    学习笔记:mysqli预处理和事务处理
    学习笔记:mysql
    学习笔记:基础+文件操作(上传|下载)+面向对象+xml
    学习笔记:php+mysql
    学习及求职心得|PHP学习心得|IT从业者的几点体会
    flash做登录页传递值给asp.net,其他语言的也可以参照下
    rpm安装依赖问题
    让进程在后台可靠运行
  • 原文地址:https://www.cnblogs.com/pacino12134/p/11054488.html
Copyright © 2011-2022 走看看