C++中数字与字符串转换

数字与字符串的转换有很多种方式,大家可以通过百度查到很多种方法。在这里,我简单介绍一下我比较喜欢用的方式。

字符串转换为数字:

#include <iostream>
#include <string>//包含stoi的头文件
using namespace std;
int main()
{
 //stoi() 是将字符串转换为整型,在C语言中我们用的是atoi(),
 //当然也可以转换为浮点类型等,只是那时我们不能用stoi(),
 //相应的方法可以去C++语言参考手册中查找 http://www.cplusplus.com/reference/string/stoi/
	string str = "123";
	int val = stoi(str);//stoi()的参数是const string*  stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!
	cout << "the digit is:" << val << endl;
	return 0;
}

数字转换为字符串:

#include<iostream>
#include <string>//同样需要此头文件
using namespace std;
int main()
{
	int a = 123;
	string str = to_string(a);//将数字转化为字符串     std::to_string是C++标准(2011年)的最新版本中引入的功能。旧的编译器可能不支持它。
	cout << "the string is:" << str << endl;
	return 0;
}
发布了11 篇原创文章 · 获赞 2 · 访问量 620

猜你喜欢

转载自blog.csdn.net/Cheng_XZ/article/details/102599030
今日推荐