2012-01-24 28 views
2

我正在尝试将数值写入与列对齐的文本文件中。我的代码如下所示:如何将填充零添加到写入流的数字中?

ofstream file; 
file.open("try.txt", ios::app); 
file << num << "\t" << max << "\t" << mean << "\t << a << "\n"; 

它可以工作,除非值不具有相同的数字位数,否则它们不会对齐。我想要的是以下内容:

1.234567 -> 1.234 
1.234  -> 1.234 
1.2  -> 1.200 
+0

[C++ stream output with 3 digits digits after the decimal point。如何?](http://stackoverflow.com/questions/8554441/c-stream-output-with-3-digits-after-the-decimal-point-how) –

回答

5

这取决于你想要的格式。对于一个固定的小数位, 是这样的:

class FFmt 
{ 
    int myWidth; 
    int myPrecision; 
public: 
    FFmt(int width, int precision) 
     : myWidth(width) 
     , myPrecision(precision) 
    { 
    } 
    friend std::ostream& operator<<(
     std::ostream& dest, 
     FFmt const& fmt) 
    { 
     dest.setf(std::ios::fixed, std::ios::floatfield); 
     dest.precision(myPrecision); 
     dest.width(myWidth); 
    } 
}; 

应该做的伎俩,所以你可以写:

file << nume << '\t' << FFmt(8, 2) << max ... 

(或任何宽度和精度你想要的)。

如果你在做任何浮点工作,你应该在你的工具包中有这样一个操纵器(尽管在很多情况下,它会更适合使用逻辑操纵器,以逻辑命名它所格式数据的含义,例如程度,距离等)。

恕我直言,它也值得扩展操纵器,以便它们保存 格式化状态,并在完整表达式的末尾恢复它。 (我的所有操纵器都是从处理此操作的基类派生出来的。)

2

您需要首先更改精度。

有一个很好的例子here

+0

答案是你的第一个 – andrea

+0

你需要指定输出是固定格式,然后指定精度,并指定每个输出的宽度。 –

+0

谢谢,安德烈,但我建议接受[詹姆斯的答案](http://stackoverflow.com/a/8985852/255756)。它更详细。 –