【问题标题】:C++ stringstream conversion to double with operator>>C++ stringstream 转换为 double 与 operator>>
【发布时间】:2016-08-24 10:46:27
【问题描述】:

我正在尝试通过重载流输入运算符来读取 C++ 中的列文件。 这是读取文件中每一行的主要函数:

#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>

using namespace std;
typedef vector <double> record_t;

istream& operator >> ( istream& ins, record_t& record )
{
  record.clear();

  string line;
  getline( ins, line );

  stringstream ss( line );
  double f;
  while (ss >> f)
    record.push_back(f);

  return ins;
}

在大多数情况下效果都很好。
但是对于这一行

55000.003520    -0.009740   0.000721    -0.024600   0.000000

第一个字段存储为55000.0 而不是55000.003520
有什么办法可以让它读取所有有效数字的正确值?

提前感谢您的帮助!

【问题讨论】:

  • 你如何检查只存储了 55000.000000?!因为这看起来就像你用来输出实际值的东西只是四舍五入到六位有效数字。
  • 我的错误,如果我用cout &lt;&lt; setprecision(15) &lt;&lt; t[0]; 打印输出值,它会显示55000.00352。感谢您的提示!
  • 你也可以使用std::fixed

标签: c++ stringstream


【解决方案1】:

将问题的答案存档:

该数字实际上已正确读入并存储。 OP 检查的方式是简单地将其通过管道传递给cout,它的默认输出精度非常有限,因此许多数字只是“四舍五入”以进行打印。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多