string与int的相互转换C++(转)

string与int之间的相互转换C++(转)

#include<iostream>
#include<string>
#include<sstream>


using namespace std;

int main()
{
    ///   string 转为 int
    string str="1234";
    int n;
    istringstream iss;//istringstream从string读入,和cin一样仅仅重载了>>,可以把string转为int
    iss.clear();//每次使用前先清空
    iss.str(str);
    iss>>n;//将输入流中的内容写入到int n,
    cout<<n<<endl;

       int 转为 string

    n=111;
    ostringstream oss;//用于向string写入,和cout<<一样,仅仅重载了<<
    oss<<n;
    str=oss.str();
    cout<<str<<endl;


    /  string 转为  int
    str="22222";
    sscanf(str.c_str(),"%d",&n);  //scanf前面加s用于把str输入到n中
    cout<<n<<endl;


    ///   int 转为 string


    int   ss=1000;
    char   temp[64];
    sprintf(temp,"%d",ss); //printf前面加s用于将ss按整数形式输出到数组temp中,不能直接给str.c_str();
    str=temp;//再把数组temp赋值给str;
    cout<<str<<endl;
    return 0;
}

  原文地址:http://www.cnblogs.com/wang7/archive/2012/04/17/2454470.html

转载于:https://www.cnblogs.com/cloudPython/p/4909970.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值