我找不到有关如何使用已打开的 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 都是 double 我试过做
f << setprecision(4) << p.price << endl;
但这不起作用。我如何格式化这个 double 为两位小数的精度。像这个 "#.00"
。如何使用特定的 fstream 来实现这一点?另外,仅供引用,总体任务是简单地读取 txt 文件,将数据存储在结构中,将结构添加到 vector ,然后从结构中读取以打印到输出文件。输入文件已经具有格式为 10.00、2.00 等(2 个小数位)的 double
最佳答案
尝试使用
#include <iomanip> // std::setprecision()
f << fixed << setprecision(2) << endl;
set precision 设置有效位数,而不是小数位数。例如cout << setprecision(3) << 12.3456 << endl;
将输出 12.3首先发送固定使得您可以从固定位置(小数位)而不是从浮点值的第一位设置精度。
关于c++ - 使用 fstream 设置精度以输出文件 - 格式为 double,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35029233/