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

Chi*_*isx 4 c++ precision 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;

   }
}
Run Code Online (Sandbox Code Playgroud)

其中p是称为product_record的结构,而价格,税金,sANDh和total都是我尝试做的两倍,f << setprecision(4) << p.price << endl;但这是行不通的。我如何格式化此双精度以具有两位小数的精度。这样"#.00"。如何使用专门的fstream实现此目的?

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

小智 9

尝试使用

f << fixed << setprecision(2) << endl;
Run Code Online (Sandbox Code Playgroud)

set precision设置有效位数,而不是小数位数。例如

cout << setprecision(3) << 12.3456 << endl;
Run Code Online (Sandbox Code Playgroud)

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