Equivalent of %02d with std::stringstream?(相当于 %02d 与 std::stringstream?)
问题描述
我想以 printf 的 %02d 的等效格式将整数输出到 std::stringstream.有没有比以下更简单的方法来实现这一点:
I want to output an integer to a std::stringstream with the equivalent format of printf's %02d. Is there an easier way to achieve this than:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
是否可以将某种格式标志流式传输到 stringstream,例如(伪代码):
Is it possible to stream some sort of format flags to the stringstream, something like (pseudocode):
stream << flags("%02d") << value;
推荐答案
您可以使用 <iomanip> 中的标准操纵器,但没有一个可以同时完成 fill 和 width 一次:
You can use the standard manipulators from <iomanip> but there isn't a neat one that does both fill and width at once:
stream << std::setfill('0') << std::setw(2) << value;
编写自己的对象在插入流中时执行这两个功能并不难:
It wouldn't be hard to write your own object that when inserted into the stream performed both functions:
stream << myfillandw( '0', 2 ) << value;
例如
struct myfillandw
{
myfillandw( char f, int w )
: fill(f), width(w) {}
char fill;
int width;
};
std::ostream& operator<<( std::ostream& o, const myfillandw& a )
{
o.fill( a.fill );
o.width( a.width );
return o;
}
这篇关于相当于 %02d 与 std::stringstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:相当于 %02d 与 std::stringstream?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
