1、使用c标准库
atoi();
atof();
#include <cstdlib>
#include <iostream>
#include <string>
int main()
{
string str = "123";
int num_int = atoi(str.c_str());
if (errno == ERANGE) //可能是std::errno
{
//number可能由于过大或过小而不能完全存储
}
else if (errno == EINVAL)
//可能是EINVAL
{
//不能转换成一个数字
}
}
2、使用c++库中的stringstream
特别注意的是,当连续使用同一个流对象去进行类型转换前!
要记得使用clear(),清除缓存,否则会导致异常结果!
#include <sstream>
#include <string>
std::string text = "152";
int number;
std::stringstream ss;
ss << text;//可以是其他数据类型
ss >> number; //string -> int
if (! ss.good())
{
//错误发生
}
ss.clear(); // clear!!!
ss << number;// int->string
string str = ss.str();
if (! ss.good())
{
//错误发生
}
使用类型模板!!!
template<class T>
void to_string(string & result,const T& t)
{
ostringstream oss;//创建一个流
oss<<t;//把值传递如流中
result=oss.str();//获取转换后的字符转并将其写入result
}
to_string(s1,10.5);//double到string
to_string(s2,123);//int到string
to_string(s3,true);//bool到string