如何使用具有类似 printf 格式的 C++ std::ostream?
我正在学习 C++.cout
是 std::ostream
类的一个实例.如何用它打印格式化的字符串?
I am learning C++. cout
is an instance of std::ostream
class.
How can I print a formatted string with it?
我仍然可以使用 printf
,但我想学习一种可以利用所有 C++ 优点的正确 C++ 方法.我认为 std::ostream
应该可以做到这一点,但我找不到正确的方法.
I can still use printf
, but I want to learn a proper C++ method which can take advantage of all C++ benefits. I think this should be possible with std::ostream
, but I can't find the proper way.
推荐答案
你可以直接用 std::ostream
做的唯一事情就是众所周知的 <<
-语法:
The only thing you can do with std::ostream
directly is the well known <<
-syntax:
int i = 0;
std::cout << "this is a number: " << i;
还有各种 IO 操纵器可用于影响整数、浮点数等的格式、位数等.
And there are various IO manipulators that can be used to influence the formatting, number of digits, etc. of integers, floating point numbers etc.
但是,这与 printf
的格式化字符串不同.C++11 不包括任何允许您以与 printf
相同的方式使用字符串格式的工具(除了 printf
本身,您当然可以如果需要,可以在 C++ 中使用).
However, that is not the same as the formatted strings of printf
. C++11 does not include any facility that allows you to use string formatting in the same way as it is used with printf
(except printf
itself, which you can of course use in C++ if you want).
就提供 printf
风格功能的库而言,有 boost::format
,它启用了这样的代码(从概要复制):
In terms of libraries that provide printf
-style functionality, there is boost::format
, which enables code such as this (copied from the synopsis):
std::cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50;
另请注意,有一个 提案在标准的未来版本中包含 printf
样式格式.如果这被接受,可能会出现如下语法:
Also note that there is a proposal for inclusion of printf
-style formatting in a future version of the Standard. If this gets accepted, syntax such as the below may become available:
std::cout << std::putf("this is a number: %d
",i);
相关文章