温馨提示×

温馨提示×

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

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

替代printf,C++ format函数实战

发布时间:2024-10-10 19:20:36 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

printf 是 C 语言中常用的格式化输出函数,而 C++ 中也有一个类似的功能,叫做 std::format。这个函数在 C++11 标准中被引入,提供了与 printf 类似的功能,但语法更加简洁和现代化。下面是一些使用 std::format 的实战示例:

示例 1:基本格式化

#include <iostream>
#include <format>

int main() {
    int age = 25;
    double salary = 5000.5;
    std::string name = "Alice";

    std::string output = std::format("Name: {}, Age: {}, Salary: {:.2f}", name, age, salary);
    std::cout << output << std::endl;

    return 0;
}

在这个例子中,std::format 使用了占位符 {} 来表示要插入的值。对于浮点数 salary,我们使用了 {:.2f} 来指定输出格式,即保留两位小数。

示例 2:位置参数

std::string output = std::format("Name: {}, Age: {}, Salary: {}", name, age, salary);

在这个例子中,我们没有指定占位符的位置,因此它们会根据传入参数的顺序自动排列。

示例 3:命名参数(C++20)

在 C++20 中,std::format 增加了对命名参数的支持,这使得代码更加清晰和易于维护。

#include <iostream>
#include <format>

int main() {
    int age = 25;
    double salary = 5000.5;
    std::string name = "Alice";

    std::string output = std::format(name, "Name: {}, Age: {}, Salary: {:.2f}", age, salary);
    std::cout << output << std::endl;

    return 0;
}

注意:上面的示例代码有误,因为 std::format 不支持直接使用变量名作为占位符。实际上,我们应该这样使用命名参数:

std::string output = std::format("{name}, Age: {age}, Salary: {salary:.2f}", {"name", name}, {"age", age}, {"salary", salary});

然而,这种方式相对繁琐。更好的方式是使用一个结构体来封装这些值,然后将其作为单个参数传递给 std::format

示例 4:使用结构体和命名参数(C++20)

#include <iostream>
#include <format>
#include <tuple>

struct Person {
    std::string name;
    int age;
    double salary;
};

int main() {
    Person person = {"Alice", 25, 5000.5};

    std::string output = std::format("Name: {}, Age: {}, Salary: {:.2f}", person.name, person.age, person.salary);
    std::cout << output << std::endl;

    return 0;
}

在这个例子中,我们定义了一个 Person 结构体来封装人的信息,然后将其作为单个参数传递给 std::format。这种方式更加清晰和易于维护。

向AI问一下细节

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

c++
AI