在使用C++编程过程中,string转为int, float, double是极为常见的操作,本文进行必要的总结,以供参考。
第一种方法:使用对应的函数
使用atoi()、 atil() 、atof()函数 进行转换,其中atoi()是将string转为int型,atol()是将string转为long int型,atof()是将string转为double型。注意一点:atof()并不会将string转为float型,再转为double型后可以强制转换为float型。具体代码如下所示:
#include <iostream>
#include <windows.h>
#include <string>
int main()
{
std::string getdata = "1234";
int n_Val = std::stoi(getdata);
int l_Val = std::stoi(getdata);
std::cout << n_Val << std::endl;
std::cout << l_Val << std::endl;
std::string getdata = "1234.000";
int d_Val = std::stof(getdata);
std::cout << d_Val << std::endl;
system("pause");
return 0;
}
第二种方法:使用stringstream
此方法即使用istringstream 函数进行数据的转换。此方法适用性较强,作者一般使用此种方法。
#include <iostream>
#include <sstream> //使用stringstream需要引入这个头文件
using namespace std;
int main()
{
int a;
float b;
string a_str = "123";
string b_str = "333.2";
istringstream isa_str(a_str);
isa_str >> a;
istringstream isb_str(b_str);
isb_str >> b;
cout << a << " " << b << endl;
return 0;
}