#include <iostream>
#include <format>
int main() {
// 使用 std::format 进行格式化输出
std::string name = "World";
int number = 42;
// 基本的字符串格式化
std::string formattedString = std::format("Hello, {}!", name);
std::cout << formattedString << std::endl;
// 包含多个参数的格式化
std::string complexFormat = std::format("The answer is {} and the name is {}", number, name);
std::cout << complexFormat << std::endl;
// 使用命名参数进行格式化
std::string namedFormat = std::format("Name: {name}, Number: {number}",
std::format_args(named_arg(name), named_arg(number)));
std::cout << namedFormat << std::endl;
return 0;
}
#include <format> 是 C++20 引入的标准库头文件,用于支持格式化字符串。std::format 函数可以轻松地将变量插入到字符串中,类似于 Python 的 f-string 或 str.format() 方法。std::format,并按照顺序插入到占位符 {} 中。std::format 支持命名参数,通过 named_arg 可以指定参数名称,使代码更易读。请注意,std::format 是 C++20 引入的功能,确保你的编译器支持 C++20 标准。
上一篇:c++基础语法
下一篇:c++ vector 初始化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站