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

标签 c++ padding ofstream

我想使用 ofstream << 将 float 写入文件,并在数字为正数时包含一个空格,例如您使用

的方式
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 方面: (此实现的灵感来自 cppreference 上的 the example)

// 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;

参见 live demo . 这样,您就可以重用代码。

关于c++ - 如何使用 << 添加一个空格来填充带有 ofstream 的减号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54587364/

相关文章:

c++ - 经过最后一个数组元素末尾的指针是否等于经过整个数组末尾的指针?

html - 在保持 parent 填充的同时使 child 可滚动

CSS 填充无法正常工作

c++ - 如何在不清除文件的情况下使用 ofstream 多次写入文件?

c++ - 是否可以简化这种基于分支的 vector 数学运算?

c++ - 调试一个大的双数组

C++ 数组,平均值(初级)

c - 为什么标准不要求最小化struct成员?

c++ - fstream、ofstream、传递文档名称、C++

c++ - 是否定义了 ofstream 实现的默认模式?