使用 fstream 设置精度以输出文件 - 双精度格式

Set precision with fstream to output file - format double

我找不到关于如何使用已打开的 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 << setprecision(4) << p.price << endl; 但这并没有工作。我如何将此双精度格式设置为小数点后两位的精度。像这样"#.00"。我如何专门使用 fstream 来实现这一点?

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

尝试使用

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

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

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

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

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