c++ - 如何使用具有类似 printf 格式的 C++ std::ostream?

我正在学习 C++。 coutstd::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/

相关文章:

coding-style - 线宽格式标准

emacs - 在 Emacs 中,如何在一系列初始化语句中排列等号?

c# - 如何格式化 Visual Studio 2012 中的所有文件?

eclipse - 格式化后无法删除 Eclipse 中的 block 注释

formatting - 复制/粘贴到 Word 时如何保留 rstudio 的格式?

java - String.format 或类似的正确格式字符串

python - 从 Python 日期/时间获取 "2:35pm"而不是 "02:35PM"?

android - 点后 2 位 float

documentation - reStructuredText 中粗体字的一部分

c#-3.0 - 如何在 Resharper 中更改 "Use Object Initializer