C++标准库format函数入门

发布时间:2024-10-10 18:58:34 作者:小樊
来源:亿速云 阅读:78

std::format 是 C++20 中引入的一个新特性,它提供了一种类型安全且易于使用的方式来格式化字符串。这个函数类似于 Python 的 str.format 或 C# 的 string.Format,但它是 C++ 标准库的一部分。

基本用法

std::format 的基本语法如下:

std::string formatted_string = std::format("{0} {1} {2}", arg1, arg2, arg3);

在这个例子中,{0}{1}{2} 是占位符,它们将被 arg1arg2arg3 的值替换。

参数类型

std::format 支持多种类型的参数,包括:

格式说明符

std::format 支持一些基本的格式说明符,如:

你还可以使用 %n 来插入换行符。

示例

下面是一些使用 std::format 的示例:

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

int main() {
    int a = 123;
    float b = 456.789f;
    std::string s = "hello";

    std::string formatted = std::format("Integer: %d, Float: %.2f, String: %s", a, b, s);
    std::cout << formatted << std::endl;

    return 0;
}

在这个例子中,%.2f 指定了浮点数 b 的精度为 2 位小数。输出将是:

Integer: 123, Float: 456.79, String: hello

注意:由于 std::format 返回的是 std::string 类型,因此你可以像处理任何其他字符串一样处理它。

推荐阅读:
  1. 指针函数在观察者模式中的实现
  2. 指针函数与C++中的工厂模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:自定义C++ format格式化器

下一篇:C++中format的灵活使用场景

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》