函數————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.  }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM