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

How to convert strings to doubles in C++ using stringstream

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

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

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

        15000000
62658722.54
91738635.67
        20
        29230756.5
        12

转换后的双打(tempDob 的 cout):

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

如何通过stringstream将这些字符串正确转换为double?谢谢!

像这样:

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

尽管您自己的代码当然会有错误处理。

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

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";
}