C++ int与string的相互转换

本文详细介绍了在C++中如何将整型(int)转换为字符串(string),以及如何将字符串(string)或字符数组(char[])转换为整型(int)。通过使用to_string函数、字符串流stringstream以及C语言的atoi函数,提供了多种实现方式,适合不同场景的需求。

一、int 转 string

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    //to_string()函数
    int p = 526103;
    string str = to_string(p);
    cout << "This is a string "  << str <<endl;

    //字符串流stringstream
    int k = 45615474; string s;
    stringstream sm;
    sm << k;
    sm >> s;
    cout << "This is a string "  << s <<endl;
    return 0;
}

 二、string、char[ ] 转 int

#include <bits/stdc++.h>
using namespace std;
int main()
{
    //C语言atoi()函数
    char st[] = "17";
    int p = atoi(st);
    cout << "This is a number " << p << endl;

    //string类型要用c_str()转化一下
    string a = "100", b = "-123";
    int c = atoi(a.c_str()) + atoi(b.c_str());
    cout << "This is a number " << c << endl;

    //字符串流stringstream
    string s = "185623";
    stringstream sm; int k;
    sm << s;
    sm >> k;
    cout << "This is a number " << k << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值