如何使用 << 添加一个空格来填充带有 ofstream 的减号?
How to add a single space to pad for a minus sign with ofstream using <<?
我想使用 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;
观看现场演示。这样,您可以重用代码。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用用户输入在C++中正确填充2D数组
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何找到大小'x'数组是否完全填充,在C++?
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 通过for循环使用用户输入填充列表
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 如何正确填充在堆上分配的二维数组?
- 将数字转换为填充字符串
- 有没有办法在一行中填充矢量图
- 用C++中的数字和条件填充向量
- 用真值填充矢量
- 使用结构成员指针在C++中填充结构
- 流填充字符的默认定位
- 使用不同算法的 PKCS1v15 填充进行加密 ++ 签名
- C++:使用缓冲区中的数据填充结构
- 以x的倍数填充前导零,使用std::cout<<std::十六进制