我对C++很陌生,我正在编写一个程序,该程序需要一个与Python%运算符做同样事情的运算符。C++中有等价物吗?
C++20std::format
库可用于此目的:
#include <iostream> #include <format> int main() { std::cout << std::format("Hello {}!n", "world"); }
有关如何使用它的更多信息和指南,请参阅:
- https://en.cppreference.com/w/cpp/utility/format
- https://www.bfilipek.com/2020/02/extra-format-cpp20.html
- https://www.zverovich.net/2019/07/23/std-format-cpp20.html
- 如何使用C++20 std::格式
但是,一些标准库实现中还没有提供<format>
——请参阅C++20库特性。在此期间,您可以使用https://github.com/fmtlib/fmt,这是等价的(并且是<format>
的灵感来源(。
C++有几种执行IO的方法,主要是由于历史原因。无论你的项目使用哪种风格,都应该始终如一地使用。
- C样式IO:printf、sprintf等
#include <cstdio>
int main () {
const char *name = "world";
// other specifiers for int, float, formatting conventions are avialble
printf("Hello, %sn", name);
}
- C++风格IO:iostreams
#include <iostream>
int main() {
std::string name = "world";
std::cout << "Hello, " << name << std::endl;
}
- 库/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说明符也可以工作。
printf("%i", 123456789);