今天遇到一个int类型数据转换为string,查了资料在c++11标准中增加了全局函数std::to_string来实现该功能:
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);
运行结果:
std::to_string()函数的实现部分:
1 //实现to_string函数2 #include<iostream>3 #include<string>4 using namespace std;5 #define max 1006 string to_String(int n)7 {8 int m = n;9 char s[max]; 10 char ss[max]; 11 int i=0,j=0; 12 if (n < 0)// 处理负数 13 { 14 m = 0 - m; 15 j = 1; 16 ss[0] = '-'; 17 } 18 while (m>0) 19 { 20 s[i++] = m % 10 + '0'; 21 m /= 10; 22 } 23 s[i] = '\0'; 24 i = i - 1; 25 while (i >= 0) 26 { 27 ss[j++] = s[i--]; 28 } 29 ss[j] = '\0'; 30 return ss; 31 }