C++中int与string的相互转换

 一、int转string

  1. c++11标准增加了全局函数std::to_string:
  2. 采用sstream中定义的字符串流对象来实现

二、string转int的方式

  1. 采用标准库中atoi函数。
  2. 采用sstream头文件中定义的字符串流对象来实现转换。
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string
#include <sstream>    // ostringstream

using namespace std;

int main()
{
	//c++11标准增加了全局函数std::to_string:
	int ix = 12;
	std::string s = std::to_string(ix);
	std::string str_ix = "ix is " + s;
	std::string str_sum = "sum is " + std::to_string(1 + 2 + 4 + 7 + 14);
	std::cout << str_ix << '\n';
	std::cout << str_sum << '\n';

	//采用sstream中定义的字符串流对象来实现
	ostringstream os;         //构造一个输出字符串流,流内容为空 
	os << ix;                 //向输出字符串流中输出int整数i的内容 
	cout << os.str() << endl; //利用字符串流的str函数获取流中的内容

	//使用std::stoi / stol / stoll等等函数
	std::string str_dec = "2001, A Space Odyssey";
	std::string str_hex = "40c3";
	std::string str_bin = "-10010110001";
	std::string str_auto = "0x7f";

	std::string::size_type sz;   // alias of size_t

	int i_dec = std::stoi(str_dec, &sz);
	int i_hex = std::stoi(str_hex, nullptr, 16);
	int i_bin = std::stoi(str_bin, nullptr, 2);
	int i_auto = std::stoi(str_auto, nullptr, 0);

	std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
	std::cout << str_hex << ": " << i_hex << '\n';
	std::cout << str_bin << ": " << i_bin << '\n';
	std::cout << str_auto << ": " << i_auto << '\n';

	//采用标准库中atoi函数, 对于其他类型也都有相应的标准库函数,比如浮点型atof(), long型atol()等等
	int a = atoi(s.c_str());
	std::cout << a << endl;
	
	//采用sstream头文件中定义的字符串流对象来实现转换
	istringstream is(s); //构造输入字符串流,流的内容初始化为“12”的字符串 
	is >> a; //从is流中读入一个int整数存入i中
	std::cout << a << endl;
	return 0;
}
ix is 12
sum is 28
12
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
12
12
请按任意键继续. . .

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JoannaJuanCV

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值