我正在尝试将数值写入与列对齐的文本文件中。我的代码如下所示:
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 :(得分: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 ...
(或者你想要的任何宽度和精度)。
如果你正在做任何浮点工作,你应该可以 在你的工具包中有这样一个操纵器(虽然在很多情况下,它会是 更合适的是使用逻辑操纵符,以逻辑命名 它格式化的数据的含义,例如学位,距离等。)。
恕我直言,它也值得扩展操纵者,以便他们拯救 格式化状态,并在完整表达式结束时将其还原。 (我的所有操纵器都来自一个处理这个问题的基类。)答案 1 :(得分:4)
答案 2 :(得分:2)
您需要先改变精度。
有一个很好的例子here。
答案 3 :(得分:2)
该方法与使用cout
时的方法相同。请参阅this answer。