主要是用到字符流istringstream ostringstream的特性
//string to double. The same way works for string to int.
double string_to_double(string s)
{
istringstream stream;
stream.str(s);
double x = 0;
stream >> x;
return x;
}
stoi方法(类似有stod方法):
string year = "2022";
int y = stoi(year);//得到数值2022
//double to string
//先创建ostringstream对象,然后使用 << 运算符向流中添加一个数,该数会被转换为一个字符序列
string double_to_string(double d)
{
ostringstream stream;
stream << d;
return stream.str();
}
同时可以向流中添加流操纵符:
ostringstream strm;
strm << fixed << setprecision(3) << 10.0 / 3;
//Similar code: strm << setw(20) << left << name << setw(11) << right << phone_number << endl;
string output = strm.str();//str成员函数从流中得到字符串
//Output: 3.333