我正在学习 C++。 cout
是 std::ostream
类的一个实例。
如何用它打印格式化的字符串?
我仍然可以使用 printf
,但我想学习一种可以利用所有 C++ 优点的正确 C++ 方法。我认为 std::ostream
应该可以做到这一点,但我找不到正确的方法。
最佳答案
你唯一能用 std::ostream
做的事直接就是众所周知的<<
-语法:
int i = 0;
std::cout << "this is a number: " << i;
还有各种IO manipulators可用于影响整数、 float 等的格式、位数等。
但是,这与 printf
的格式化字符串不同。 . C++11 不包含任何允许您以与 printf
相同的方式使用字符串格式化的工具。 (printf
本身除外,如果你愿意,当然可以在 C++ 中使用它)。
就提供 printf
的库而言风格的功能,有 boost::format
,它启用了这样的代码(从概要复制):
std::cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50;
另请注意,有一个 proposal for inclusion的 printf
- 标准 future 版本中的样式格式。如果这被接受,可能会出现如下语法:
std::cout << std::putf("this is a number: %d\n",i);
https://stackoverflow.com/questions/15106102/