C++ string->int & int->string

如果你是在C++11之前,可能比较麻烦

string->int  (#include <cstdlib>)

string s( "123");
int a = atoi(s. c_str());
cout << a;

int->string

1.使用stringstream  (#include <sstream>)

stringstream ss;
ss << 12;
string s;
ss >> s;
cout << s;

2.使用sprintf

char c_str[ 100];
sprintf(c_str, "%d", 12);
string s(c_str);
cout << s;

而C++11中提供了更简单的方案:

string->int

string s = "123";
int a = std::stoi(s);
cout << a;

函数原型在这

  int stoi (const string& str, size_t* idx = 0, int base = 10);

就是要注意的是,这里的idx是个指针,而非下标,指向开始转换的地方

当然,你也可以很自然的想到,还有


int->string

int a = 123;
string s = std::to_string(a);
cout << s;

转成string SO EASY~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值