相当于%02d与std :: stringstream? [英] Equivalent of %02d with std::stringstream?
本文介绍了相当于%02d与std :: stringstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想输出一个整数到 std :: stringstream
,其等效格式为 printf
code>%02d 。是否有一个更简单的方法来实现这:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文