【发布时间】:2016-01-27 05:00:47
【问题描述】:
我找不到如何使用已打开的 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 位小数)的双精度数
【问题讨论】:
-
好吧,我的错,我一秒钟就打出来。
-
f << std::fixed << std::setprecision(2); -
在无缘无故公然否决投票之前,请尝试提供建设性的批评。谢谢@user657267 我会试试的。
标签: c++ double precision fstream