Python 中 % 或 .format 运算符的 C++ 等价物是什么?

What is the C++ equivalent of the % or .format operator in Python?

我是 C++ 的新手,我正在编写一个程序,该程序需要一个与 Python % 运算符执行相同操作的运算符。 C++ 中是否有任何等效项?

C++20 std::format 库用于此目的:

#include <iostream>
#include <format>
 
int main() {
    std::cout << std::format("Hello {}!\n", "world");
}

有关如何使用它的更多信息和指南,请参阅:

但是,<format> 尚未在某些标准库实现中提供 — 请参阅 C++20 library features. In the meantime you can use https://github.com/fmtlib/fmt,它是等效的(并且是 <format> 的灵​​感来源)。

C++ 有几种实现 IO 的方法,主要是出于历史原因。无论您的项目使用哪种风格,都应始终如一地使用。

  1. C 风格的 IO:printf、sprintf 等
#include <cstdio>

int main () {
  const char *name = "world";
  // other specifiers for int, float, formatting conventions are avialble
  printf("Hello, %s\n", name); 
}
  1. C++ 风格的 IO:iostreams
#include <iostream>

int main() {
  std::string name = "world";
  std::cout << "Hello, " << name << std::endl;
}
  1. Libraries/C++20 std::format:

Pre C++20 很多人已经提供了他们自己的格式化库。其中一个较好的是 {fmt}。 C++ 采用这种格式为 [std::format][2]

#include <format>
#include <iostream>
#include <string>

int main() {
  std::string name = "world";
  std::cout << std::format("Hello, {}", name) << std::endl;
}

请注意 format 会生成格式字符串,因此它适用于两种执行 IO 的方式,and/or 其他自定义方法,但如果您使用 C 风格的 IO,则分层 std::format 在上面,这里 printf 说明符也可以工作。

printf("%i", 123456789);