C/C++数字和字符串的转换

本文详细介绍了两种在C++中实现字符串与数字相互转换的方法:使用stringstream和sprintf()/sscanf()函数。通过具体代码示例,展示了如何将整数转换为字符串以及如何将字符串解析为整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天,我在做题时候,遇到了字符串和数字之间的转换,现将转换的方法总结如下。

1、利用stringstream

数字转换成字符串

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
	int num=521;
	string result;
	stringstream temp;//定义流temp 
	temp<<num;//将数字转化成流temp 
	temp>>result;//再将流temp转化成字符串 
	return 0;
}

字符串转化成数字

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
	string str="521";
	int num;
	stringstream temp;//定义流temp 
	temp<<str;//将字符串转化成流temp 
	temp>>num;//再将流temp转化成数字 
	return 0;
}

2、利用sprintf()和sscanf()函数

数字转换成字符串

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	int num=521;
	char str[10];
	sprintf(str,"%d",num);
	return 0;
}

字符串转化成数字

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	char str[]="521";
	int num;
	sscanf(str,"%d",&num);
	return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值