如何使用 << 添加一个空格来填充带有 ofstream 的减号?

How to add a single space to pad for a minus sign with ofstream using <<?

本文关键字:lt 填充 ofstream 一个 添加 何使用 空格      更新时间:2023-10-16

我想使用 ofstream 将浮点数<<到文件中,并在数字为正时包含一个空格,例如,使用

printf("% .3f",number),

以确保它们对齐。如何格式化<<以包含单个符号空间?

标准库中似乎没有一个。如果您不介意冗长,只需手动以直接的方式进行操作:

if (std::signbit(number) == false) // to avoid traps related to +0 and -0
    std::cout << " ";
std::cout << number;

(别忘了#include <cmath> signbit

但这更像是一种"解决方法"。您还可以重新实现num_put方面:(此实现的灵感来自 CPP首选项的示例(

// a num_put facet to add a padding space for positive numbers
class sign_padding :public std::num_put<char> {
public:
    // only for float and double
    iter_type do_put(iter_type s, std::ios_base& f,
                     char_type fill, double v) const
    {
        if (std::signbit(v) == false)
            *s++ = ' ';
        return std::num_put<char>::do_put(s, f, fill, v);
    }
};

并像这样使用它:

// add the facet to std::cout
std::cout.imbue(std::locale(std::cout.getloc(), new sign_padding));
// now print what you want to print
std::cout << number;

观看现场演示。这样,您可以重用代码。