本文介绍了设置精度与fstream到输出文件 - 格式双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到一个答案,我如何使用已打开的fstream输出格式化的双打到一个文本文件。目前我的代码是这样做的:

I cannot find an answer for how I might use an already opened fstream to output formatted doubles to a text file. Currently my code is doing this:

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是struct叫做product_record价格,税金,sANDh和总计都是双倍。我已尝试过 f< setprecision(4)<< p.price< endl; 但这不工作。我如何格式化这个双精度有两个小数位。像这样#。00。如何使用专门的fstream?

Where p is struct called product_record and price, tax, sANDh, and total are all doubles I have tried doing f << setprecision(4) << p.price << endl; but this does not work. How can i format this double to have a precision of two decimal places. Like this "#.00". How can I achieve this using specifically fstream?

另外,fyi,总体任务是简单地读取一个txt文件,将数据存储在结构体中,然后从结构中读取以打印到输出文件。输入文件已有10.00,2.00等格式的双精度值(

Also, fyi, the overall task is to simply read a txt file, store data in a struct, add structs to a vector and then read from the structs to print to an output file. The input file already has the doubles formatted like 10.00, 2.00 and such(2-decimal places)

推荐答案

尝试使用

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

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

set precision sets the number of significant digits, not the number of decimals places. For example

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

会输出12.3

以固定的第一个发送,精度从固定位置(小数位),而不是从浮点值的第一个数字。

would output 12.3
Sending in fixed first makes it so you are setting the precision from a fixed position (the decimal place) rather than from the first digit of the floating point value.

这篇关于设置精度与fstream到输出文件 - 格式双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 12:09