2

我对 C++ 很陌生,我正在编写一个程序,该程序需要一个与 Python % 运算符执行相同操作的运算符。C ++中有任何等价物吗?

4

3 回答 3

7

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

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

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

但是,<format>在某些标准库实现中尚未提供 - 请参阅C++20 库功能。与此同时,您可以使用https://github.com/fmtlib/fmt,它是等效的(并且是 的灵感来源<format>)。

于 2020-07-26T21:24:26.843 回答
3

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. 库/C++20 标准::格式:

在 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 和/或其他自定义方法的两种方式,但如果您使用 C 风格的 IO,将 std::format 放在顶部可能会很奇怪,其中printf 说明符也可以工作。

于 2020-07-26T21:34:11.107 回答
0
printf("%i", 123456789);
于 2020-07-26T21:34:56.563 回答