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

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

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; 
}
发布了113 篇原创文章 · 获赞 103 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Deep___Learning/article/details/103977450
今日推荐