and*_*rea 3 c++ padding ofstream
我正在尝试将数值写入与列对齐的文本文件中.我的代码看起来像这样:
ofstream file;
file.open("try.txt", ios::app);
file << num << "\t" << max << "\t" << mean << "\t << a << "\n";
Run Code Online (Sandbox Code Playgroud)
它有效,除非值没有相同的数字,否则它们不对齐.我想要的是以下内容:
1.234567 -> 1.234
1.234 -> 1.234
1.2 -> 1.200
Run Code Online (Sandbox Code Playgroud)
这取决于您想要的格式.对于固定的小数位,例如:
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 );
}
};
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩,所以你可以写:
file << nume << '\t' << FFmt( 8, 2 ) << max ...
Run Code Online (Sandbox Code Playgroud)
(或任何你想要的宽度和精度).
如果你正在做任何浮点工作,你应该在你的take kit中有这样一个操纵器(虽然在很多情况下,使用逻辑操纵器更合适,以它格式化的数据的逻辑含义命名,例如度,距离等).
恕我直言,它也值得扩展操纵器,以便它们保存格式化状态,并在完整表达式结束时恢复它.(我的所有操纵器都来自一个处理这个问题的基类.)
| 归档时间: |
|
| 查看次数: |
4080 次 |
| 最近记录: |