string类型和int类型之间的转换

一、string转int

1. 使用string流

/* 字符串转整型 */
/*
 * istringstream:从 string 读取数据 
 * ostringstream:向 string 写入数据 
 * stringstream:既可从 string 读数据,也可向 string 写数据
 */ 
void StrToInt(const string &s)
{
	int num = 0;
	stringstream ss;
	ss << s;
	ss >> num;
	cout << num << endl;
}

  

2. 采用标准库中 atoi 函数

/* 字符串转整型 */
void StrToInt(const string &s)
{
	int num = 0;
	// 将string类型先转化为const char*类型 
	const char *str = s.c_str();
	num = atoi(str);
	cout << num << endl;
}

 

3. 采用 stoi 函数

/* 字符串转整型 */
/*
 * 注:某些老版本的string不支持该函数 
 * 原型:int stoi (const string &str, size_t *idx = 0, int base = 10); 
 */ 
void StrToInt(const string &s)
{
	int num = 0;
	num = stoi(s);	// 等价于stoi(s, 0, 10); 
	cout << num << endl;
}

  

 

二、int转string

1. 使用string流

/* 整型转字符串 */
void IntToStr(int i)
{
	string s;
	stringstream ss;
	ss << i;
	ss >> s;
	cout << s << endl; 
}

  

2. 使用 sprintf 函数

/* 整型转字符串 */
/*
 * 原型:int sprintf (char *buffer, const char *format, [argument]...); 
 */ 
void IntToStr(int i)
{
	string s;
	char *str;
	sprintf(str, "%d", i);
	s = str;
	cout << s << endl; 
}

  

3. 使用 to_string 函数

/* 整型转字符串 */
/*
 * 原型:string to_string (int val);
 */ 
void IntToStr(int i)
{
	string s;
	s = to_string(i);
	cout << s << endl; 
}

  

  

转载于:https://www.cnblogs.com/xzxl/p/9605097.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值