【问题标题】:Set precision with fstream to output file - format double使用 fstream 设置精度以输出文件 - 格式为双精度
【发布时间】:2016-01-27 05:00:47
【问题描述】:

我找不到如何使用已打开的 fstream 将格式化的双精度输出到文本文件的答案。目前我的代码正在这样做:

int writeToFile (fstream& f, product_record& p)
{
   if (!f){
      cout << "out file failed!!error" << endl;
      return -1;
   } else {

      f << p.idnumber << endl;
      f << p.name << endl;
      f << p.price << endl;
      f << p.number << endl;
      f << p.tax << endl;
      f << p.sANDh << endl;
      f << p.total << endl;
      f << intArrToString( p.stations ) << endl;

   }
}

其中 p 是名为 product_record 的结构,价格、税款、sANDh 和总计都是 doubles 我尝试过 f &lt;&lt; setprecision(4) &lt;&lt; p.price &lt;&lt; endl; 但这不起作用。我如何格式化这个双精度以具有两位小数的精度。喜欢这个"#.00"。如何使用专门的 fstream 来实现这一点?

另外,仅供参考,总体任务是简单地读取 txt 文件,将数据存储在结构中,将结构添加到向量,然后从结构中读取以打印到输出文件。输入文件已经具有格式为 10.00、2.00 等(2 位小数)的双精度数

【问题讨论】:

  • 好吧,我的错,我一秒钟就打出来。
  • f &lt;&lt; std::fixed &lt;&lt; std::setprecision(2);
  • 在无缘无故公然否决投票之前,请尝试提供建设性的批评。谢谢@user657267 我会试试的。

标签: c++ double precision fstream


【解决方案1】:

尝试使用

#include <iomanip>  // std::setprecision()

f << std::fixed << setprecision(2) << endl;

std::setprecision() 设置有效位数,而不是小数位数。例如

cout << setprecision(3) << 12.3456 << endl;

将输出 12.3
首先发送固定值,这样您就可以从固定位置(小数位)而不是从浮点值的第一个数字设置精度。

【讨论】:

  • 解决了这个问题,非常感谢。我仍然有点困惑为什么没有fixed 它将无法工作。
猜你喜欢
  • 2013-03-17
  • 2010-11-28
  • 2018-03-07
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多