c++ - 使用 fstream 设置精度以输出文件 - double 格式

标签 c++ double precision fstream

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

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 的结构,price、tax、sANDh 和 total 都是 doubles 我试过 f << setprecision(4) << p.price << endl;但这不起作用。我如何将此 double 格式设置为小数点后两位的精度。像这样"#.00" .我如何使用专门的 fstream 来实现这一目标?

此外,仅供引用,总体任务是简单地读取一个 txt 文件,将数据存储在一个结构中,将结构添加到一个 vector 中,然后从结构中读取以打印到输出文件。输入文件已经具有 double 格式,如 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
首先发送固定值,这样您就可以从固定位置(小数位)而不是从浮点值的第一位开始设置精度。

关于c++ - 使用 fstream 设置精度以输出文件 - double 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35029233/

相关文章:

c++ - 线程池实现 : condition_variables vs. yield()

c - double 和整数的求和和乘法不起作用

c - 带 double 的 SSE,不值得吗?

python - 在 ndarray 中查找 float

c - 调用功能,微秒精度

c - C++ 或 C 中浮点乘法的最佳实践?

c++ - 混合使用 C、C++ 和 Fortran 代码

c++ - 32位Linux中signed long long数据类型的最大大小是多少

c++ - 从 std::vector 继承时 g++ 7 中的 undefined reference

opengl - GLSL double 角、三角函数和指数函数解决方法