我想使用 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/