最近学习c++,偶然用到int转化string,结果发现没有直接转化的函数。就收集了int转化string的集中方法。
1.
int n = 65535;
char t[10];
string s;
sprintf(t, "%d", n);
s = t;
cout << s << endl;
return 0;
使用sprintf()方法。
2.
stringstream ss;
string s;
int n = 65535;
ss<<n;
ss>>s;
cout<<s<<endl;
return 0;
使用stringstream,头文件需要include<sstream>.
3.
string int2str(int n)
{
char c[10];
int i = 0;
while (n) {
c[i++] = (n % 10) + '0';
n /= 10;
}
c[i] = 0;
i--;
int j = 0;
while(i && i > j)
{
char temp = c[i];
c[i] = c[j];
c[j] = temp;
j++;
i--;
}
return c;
}
int main() {
int n = 65535;
string str = int2str(n);
cout<<str<<endl;
return 0;
}
通过将每一位转化为字符存在字符数组中,然后将字符数组转为string。int2str()方法中首先得到的是逆序的,需要交换顺序。有一个方法strrev()可以直接逆序的,不过该方法不是标准函数,不是所有的编译器都支持,可悲我的linux下的不支持,就自己交换了。
4.
int x = 65535;
char c[10];
string s;
itoa(x,c,10);
s = c;
cout<<s<<endl;
return 0;
有一个函数itoa()可以将整数直接转换为char数组,可惜不是标准函数,又可悲的没支持。只是一种方法,不是所有编译器都支持。
我就知道这点了,大家有更好的请告诉我。3q~~