数字与字符串互转

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
    //使用C标准库里面的atoi
    //字符串转数字
    string str = "123";
    int value = std::atoi(str.c_str());
    cout << "string to int value:" << value << endl;

    //C++标准库里面,使用stringstream
    std::stringstream sstr;
    sstr << "520";
    int value2;
    sstr >> value2;
    cout<<"string to int value2:" << value2 << endl;

    //数字转字符串
    char str[10];
    int a = 1234321;
    sprintf(str,"%d",a);
    cout << str << endl;

    int value3 = 125;
    std::stringstream sstr2;
    sstr2 << value3;
    string str2;
    sstr2 >> str2;
    cout<<"int to string str2:" << str2 << endl;

    return 0;
}

stringstream sTmp;
sTmp << iJsValue["LocationID"].asInt();
string sLocationID = sTmp.str();//Int to String
const char *cLocationID = sLocationID.data();//String to char*

//关于s.c_str()
//不宜使用
char* c; 
string s="1234"; 
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理
//正确使用
char c[20]; 
string s="1234"; 
strcpy(c,s.c_str()); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值