在C++11中可以使用std::to_string()函數將數值轉換為string格式,十分方便。
以下部分來選自cplusplus.com。
string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val);Convert numerical value to string
Returns a string with the representation of val.
1 // to_string example 2 #include <iostream> // std::cout 3 #include <string> // std::string, std::to_string 4 5 int main () 6 { 7 std::string pi = "pi is " + std::to_string(3.1415926); 8 std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number"; 9 std::cout << pi << '\n'; 10 std::cout << perfect << '\n'; 11 return 0; 12 }
pi is 3.141593
28 is a perfect numbe
[1]http://www.cplusplus.com/reference/string/to_string/