C++ 字符串和整数互转

字符串和整数互转

字符串使用string
方法 1

int my_string_to_int(string s)
{
    int sum = 0;
    for (int i = 0; i < s.length(); i++)
    {
        sum = sum * 10 + (s[i] - '0');
    }
    return sum;
}
string my_int_to_string(int n)
{
    string s;
    int i = 0;
    int j = 0;
    char t;
    while (n != 0)
    {
        s.push_back(n % 10);//字符转整数
        n /= 10;
        i++;
    }
    i--;
    while (j < i)//反转字符串
    {
        // t = s[i];
        // s[i--] = s[j];
        // s[j++] = t;
        swap(s[i--], s[j++]);//交换字符
    }
    return s;
}

方法 2
stringstream

#include <sstream>
stringstream ss;
string s;
int n=123;
ss<<n;
ss>>s;

方法 3
字符串输入输出流

#include <iostream>
int n;
char t[100];
sscanf(n,"%d",t);
ssprintf(t,"%d",n);

方法4

#include<iostream>
int n=123;
char t[100];
cout<<to_string(n)<<endl;
cout << "to_string " << to_string(n) << endl;
cout << "itoa " << itoa(n, t, 10) << endl;
cout << "ltoa " << ltoa(n2, t, 10) << endl;
cout << "atoi " << atoi("123") << endl;
cout << "atol " << atol("123") << endl;
//字符串转各类数
cout << "stoi " << stoi("123") << endl;
cout << "stol " << stol("123") << endl;
cout << "stof " << stof("123") << endl;
cout << "stod " << stod("123") << endl;
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值