如何使用stringstream在C ++中将字符串转换为双精度数

时间:2016-12-11 22:47:25

标签: c++ stringstream

我正在尝试从矢量中获取字符串并使用stringstream将它们转换为双精度数。但是,当我运行此代码时:

  double tempDob;
  stringstream ss;
  ss << tempVec[3];
  ss >> tempDob;

我得到奇怪的东西,而不是正常的双倍。这是一个例子: 原始字符串(cout of tempVec [3]):

        15000000
62658722.54
91738635.67
        20
        29230756.5
        12

转换双打(cout of tempDob):

1.5e+07
6.26587e+07
9.17386e+07
2.92308e+07
4.70764e+07
3.53692e+07

如何通过stringstream将这些字符串正确转换为双精度数?谢谢!

2 个答案:

答案 0 :(得分:0)

像这样:

istringstream is( somestring );
double d;
is >> d;

虽然你自己的代码当然会有错误处理。

答案 1 :(得分:0)

您可以像这样重复使用相同的字符串流:

std::vector<std::string> theVec { "        15000000",
                                  "62658722.54",
                                  "91738635.67",
                                  "        20",
                                  "        29230756.5",
                                  "        12" };
std::stringstream ss;
for (auto const& s : theVec)
{
    ss.clear();
    ss.str(s);
    double d;
    ss >> d;
    std::cout << d << "\n";
}