如何将填充零添加到写入流的数字中
How can I add padding zeros to a number written to an ofstream?
我正试图将数值写入与列对齐的文本文件中。我的代码如下:
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
这取决于您想要的格式。对于固定的小数点,类似于:
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 ...
(或您想要的任何宽度和精度)。
如果你正在做任何浮点运算,你可能应该在你的Take工具包中有这样一个操纵器(尽管在许多情况下,它会更适合使用逻辑操纵器,以逻辑它格式化的数据的含义,例如度数、距离等)
IMHO,扩展操纵器也是值得的,这样它们就可以节省格式化状态,并在完整表达式结束时将其还原。(我所有的操纵器都派生自一个处理这个问题的基类。)
查看std::fixed
、std::setw()
和std::setprecision()
。
您需要首先更改精度。
这里有一个很好的例子。
该方法与使用cout
时相同。看看这个答案。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 在c++中用vector填充一个简单的动态数组
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何使用用户输入在C++中正确填充2D数组
- 将数字转换为填充字符串
- 用C++中的数字和条件填充向量
- C++以特定方式用数字填充矩阵
- 如何从逗号分隔的数字对中填充 2 个向量 C++.
- Qt究竟是如何处理字符串的,或者如何生成填充数字
- 用地址而不是数字填充队列
- 我需要在部分填充的数组中找到最大的数字
- 声明一个类型为String的数组,该数组包含带填充的数字
- 如果我有一个固定大小的填充ascii数字的char数组,我知道它指的是一个无符号整数,那么将其转换为无符号整数的最快方法
- 填充列表<>使用数组获取错误的数字
- 使用 std::fill 用递增的数字填充矢量
- 如何将填充零添加到写入流的数字中
- 使用函数填充数组中的数字.如果数组已满,则该数字将在第二个数组中填充
- 使用循环将数字填充矩阵A (Eigen::Matrix2d A)