在写代码时,偶然把一个char型加上‘\0‘,结果发现其实加不加都无所谓,int都能转string型。比如:
int c=48; string s0,s1; for (int i=0;i<10;i++){ s0=c+i; s1=c+i+'0'; //+'0'等价于+48 cout<<c+i+'\0'<<"~"<<s0<<"~"<<s1<<endl; }
显示结果:
48~0~`
49~1~a
50~2~b
51~3~c
52~4~d
53~5~e
54~6~f
55~7~g
56~8~h
57~9~i
--------------------------------
结论:整数与256的余数就是它转字串的那个字母的ascii码。
现在把任意整数各位上的0~9分别转字符,就能实现整数转字串itoString()了:
#include <iostream> #include <string> #include <climits> using namespace std; string itoString(int i) { int n; string s,t; if (i==INT_MIN) return itoString(INT_MIN/10)+itoString(-(INT_MIN%10)); n=i>0?i:-i; do{ t=(char)(n%10+48)+'\0'; s=t+s; n=n/10; } while(n>0); return i>0?s:"-"+s; } string ltoString(long int i) { long int n; string s,t; if (i==LONG_MIN) return ltoString(LONG_MIN/10)+ltoString(-(LONG_MIN%10)); n=i>0?i:-i; do{ t=(char)(n%10+48)+'\0'; s=t+s; n=n/10; } while(n>0); return i>0?s:"-"+s; } string lltoString(long long i) { long long n; string s,t; if (i==LONG_LONG_MIN) return lltoString(LONG_LONG_MIN/10)+lltoString(-(LONG_LONG_MIN%10)); n=i>0?i:-i; do{ t=(char)(n%10+48)+'\0'; s=t+s; n=n/10; } while(n>0); return i>0?s:"-"+s; } int main(void) { int i; long long j; cout<<"整数转字符串测试:"<<endl; for (i=-10;i<=10;i++) cout<<itoString(i)<<" "; cout<<endl<<endl; i=1234567890; cout<<i<<"转字符串:"<<itoString(i)<<endl; cout<<-i/10<<"转字符串:"<<itoString(-i/10)<<endl<<endl; j=8976543210123456789; cout<<j<<"转字符串:"<<lltoString(j)<<endl; cout<<-j/10<<"转字符串:"<<lltoString(-j/10)<<endl<<endl; cout<<"int型的数值范围是:"<<itoString(INT_MIN)<<","<<itoString(INT_MAX)<<endl; cout<<"long int型的数值范围:"<<ltoString(LONG_MIN)<<","<<ltoString(LONG_MAX)<<endl; cout<<"long long型的数值范围:"<<lltoString(LONG_LONG_MIN)<<","<<lltoString(LONG_LONG_MAX)<<endl; return 0; }
测试结果:
整数转字符串测试: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 -0 1 2 3 4 5 6 7 8 9 10 1234567890转字符串:1234567890 -123456789转字符串:-123456789 8976543210123456789转字符串:8976543210123456789 -897654321012345678转字符串:-897654321012345678 int型的数值范围是:-2147483648,2147483647 long int型的数值范围:-2147483648,2147483647 long long型的数值范围:-9223372036854775808,9223372036854775807 -------------------------------- Process exited after 0.5405 seconds with return value 0 请按任意键继续. . .
只是测试一下,因为库函数to_string()转int成字符串是非常好用的。但是它转float\double型用处不大,其返回的小数部分只保留6位,即小于0.000001的数都转成0.000000,要么四舍五入成0.000001。float\double的数还是用stringstream来转比较方便。