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

2024-04-25 23:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我对C++非常陌生,我正在编写一个程序,它需要一个和Python %操作符一样的操作符。C++中是否有等价的?


Tags: 程序等价陌生
3条回答
printf("%i", 123456789);

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++采用这种格式作为^ {CD1>}/P>

#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说明符也可以在上面工作

C++20^{}库用于此目的:

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

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

但是,在一些标准库实现中还没有提供<format>,请参见C++20 library features。同时,您可以使用https://github.com/fmtlib/fmt,这是等效的(也是<format>的灵感来源)

相关问题 更多 >

    热门问题