如何向写入 ofstream 的数字添加填充零?

发布于 2024-12-28 10:52:33 字数 364 浏览 5 评论 0原文

我正在尝试将数值写入与列对齐的文本文件中。我的代码如下所示:

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

I'm trying to write numeric values into a text file aligned to columns. My code looks like this:

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

It works, except if the values don't have the same number of digits, they don't align. What I would like is the following:

1.234567  ->  1.234
1.234     ->  1.234
1.2       ->  1.200

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

数理化全能战士 2025-01-04 10:52:33

这取决于您想要什么格式。对于固定小数位,
像这样的东西:

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 ...

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

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

恕我直言,扩展操纵器也是值得的,这样它们就可以节省
格式化状态,并在完整表达式结束时恢复它。
(我的所有操纵器都派生自处理此问题的基类。)

It depends on what format you want. For a fixed decimal place,
something like:

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 );
    }
};

should do the trick, so you can write:

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

(or whatever width and precision you want).

If you're doing any floating point work at all, you should probably have
such a manipulator in your took kit (although in many cases, it will be
more appropriate to use a logical manipulator, named after the logical
meaning of the data it formats, e.g. degree, distances, etc.).

IMHO, it's also worth extending the manipulators so that they save the
formatting state, and restore it at the end of the full expression.
(All of my manipulators derive from a base class which handles this.)

舂唻埖巳落 2025-01-04 10:52:33

您需要首先更改精度。

这里有一个很好的例子。

You'll need to alter the precision first.

There's a good example here.

你的他你的她 2025-01-04 10:52:33

方法与使用cout时相同。请参阅此答案

The method is the same as when using cout. See this answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文