C++ 与 std::stringstream 等效的 %02d?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2839592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent of %02d with std::stringstream?
提问by Andreas Brinck
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:
我想以'sstd::stringstream
的等效格式将整数输出到 a 。有没有比以下更简单的方法来实现这一目标:printf
%02d
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
Is it possible to stream some sort of format flags to the stringstream
, something like (pseudocode):
是否可以将某种格式标志流式传输到stringstream
,例如(伪代码):
stream << flags("%02d") << value;
回答by CB Bailey
You can use the standard manipulators from <iomanip>
but there isn't a neat one that does both fill
and width
at once:
您可以使用标准的机械手从<iomanip>
但没有一个整洁的一个,做两个fill
和width
一次:
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;
E.g.
例如
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;
}
回答by hpsMouse
You can use
您可以使用
stream<<setfill('0')<<setw(2)<<value;
回答by Marcelo Cantos
You can't do that much better in standard C++. Alternatively, you can use Boost.Format:
在标准 C++ 中你不能做得更好。或者,您可以使用 Boost.Format:
stream << boost::format("%|02|")%value;
回答by vitaut
Is it possible to stream some sort of format flags to the
stringstream
?
是否可以将某种格式标志流式传输到
stringstream
?
Unfortunately the standard library doesn't support passing format specifiers as a string, but you can do this with the fmt library:
不幸的是,标准库不支持将格式说明符作为字符串传递,但您可以使用fmt 库来做到这一点:
std::string result = fmt::format("{:02}", value); // Python syntax
or
或者
std::string result = fmt::sprintf("%02d", value); // printf syntax
You don't even need to construct std::stringstream
. The format
function will return a string directly.
你甚至不需要构造std::stringstream
. 该format
函数将直接返回一个字符串。
Disclaimer: I'm the author of the fmt library.
免责声明:我是fmt 库的作者。