溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

替代printf,C++ format函數(shù)實(shí)戰(zhàn)

發(fā)布時(shí)間:2024-10-10 19:20:36 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

printf 是 C 語言中常用的格式化輸出函數(shù),而 C++ 中也有一個(gè)類似的功能,叫做 std::format。這個(gè)函數(shù)在 C++11 標(biāo)準(zhǔn)中被引入,提供了與 printf 類似的功能,但語法更加簡潔和現(xiàn)代化。下面是一些使用 std::format 的實(shí)戰(zhàn)示例:

示例 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;
}

在這個(gè)例子中,std::format 使用了占位符 {} 來表示要插入的值。對于浮點(diǎn)數(shù) salary,我們使用了 {:.2f} 來指定輸出格式,即保留兩位小數(shù)。

示例 2:位置參數(shù)

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

在這個(gè)例子中,我們沒有指定占位符的位置,因此它們會(huì)根據(jù)傳入?yún)?shù)的順序自動(dòng)排列。

示例 3:命名參數(shù)(C++20)

在 C++20 中,std::format 增加了對命名參數(shù)的支持,這使得代碼更加清晰和易于維護(hù)。

#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;
}

注意:上面的示例代碼有誤,因?yàn)?std::format 不支持直接使用變量名作為占位符。實(shí)際上,我們應(yīng)該這樣使用命名參數(shù):

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

然而,這種方式相對繁瑣。更好的方式是使用一個(gè)結(jié)構(gòu)體來封裝這些值,然后將其作為單個(gè)參數(shù)傳遞給 std::format。

示例 4:使用結(jié)構(gòu)體和命名參數(shù)(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;
}

在這個(gè)例子中,我們定義了一個(gè) Person 結(jié)構(gòu)體來封裝人的信息,然后將其作為單個(gè)參數(shù)傳遞給 std::format。這種方式更加清晰和易于維護(hù)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI