C++字符串转换为数值型

引言

字符串处理中,常常需要把字符串转换成数值型。方法有很多,这里总结两种比较简单的方法。

方法一

C++自带函数atoi(char *s)

函数原型

#include<cstdlib>
atoi(char *s);

参考代码:

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{ 
	string s = "123456789";
	int ints = atoi(s.c_str());
	cout << ints;
	
	return 0;
}

《C++字符串转换为数值型》

  • 缺点是:只能转换成int型,对于double等无效。
方法二

利用stringstream字符串输入输出流

参考代码:

#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;
int main()
{ 
	double dous;
	string s = "123.456";
	stringstream ss(s);
	ss >> dous;
	cout <<"转换后: "<<dous<<endl;
	
	return 0;
}
stringstream 需要include <sstream>
  • stringstream 把字符串当作输入输出流 可以处理字符串转任意数值类型的问题。
    原文作者:GOD_Dian
    原文地址: https://blog.csdn.net/qq_39685968/article/details/104527882
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞