![](/img/trans.png)
[英]how to write into a single file (create from stream class) from two different files using 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
facet :(此實現的靈感來自cppreference上的示例 )
// 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;
查看現場演示 。 這樣,您就可以重用代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.