函数————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);
11.#include <iostream>
22.#include <string> // std::to_string
33.#include <sstream> // std::stringstream
44.int main()
55.{
66.    // old method
77.    std::stringstream ss;
88.    ss << 1.23;
99.    std::string str = ss.str();
1010.    std::cout << str << std::endl;
1111.    // new method
1212.    std::string pi = "pi is" + std::to_string(3.1415926);
1313.    std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + "is a perfect number";
1414.    std::cout << pi << std::endl;
1515.    std::cout << perfect << std::endl;
1616.    return0;
1717.}
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. }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。