C++中int转化string的几种方法

最近学习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~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值