int与string类型转化(C++)

本文介绍了C++中将整数转换为字符串的三种方法:使用stringstream、sprintf函数以及C++11的to_string和stoi函数,同时展示了如何将字符串转换回整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

int转为string

  1. 利用sstream类
#include <iostream>
#include <sstream>
using namespace std;

int main(){
    int n = 10;
    stringstream ss;
    string str;
    ss << n;
    ss >> str;
    cout << str << endl;
}

  1. sprintf
#include <iostream>
#include <string>
using namespace std;

int main(){
    int n = 10;
    char t[15];
    sprintf(t, "%d", n);  // 转成char类型
    cout << t << endl;
    string str(t);  //转成string类型
    cout << str << endl;

}
  1. to_string
    c++的版本的是C++11
#include <iostream>
#include <string>
using namespace std;

int main(){
    int m = 10;
    string str;
    str = to_string(m);
    cout << str <<endl;
}

string转int类型

  1. stoi函数
    int m = stoi(str);
    string s1 ="0123456";
    string s2 = "6543210";
    int x = stoi(s1);
    int y = stoi(s2);
    cout << x << endl;//123456
    cout << y << endl;//6543210
    string ss = "0";
    int m = stoi(ss);
    cout << m << endl;//0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值