您好,登錄后才能下訂單哦!
printf
是 C 語言中常用的格式化輸出函數(shù),而 C++ 中也有一個(gè)類似的功能,叫做 std::format
。這個(gè)函數(shù)在 C++11 標(biāo)準(zhǔn)中被引入,提供了與 printf
類似的功能,但語法更加簡潔和現(xiàn)代化。下面是一些使用 std::format
的實(shí)戰(zhàn)示例:
#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ù)。
std::string output = std::format("Name: {}, Age: {}, Salary: {}", name, age, salary);
在這個(gè)例子中,我們沒有指定占位符的位置,因此它們會(huì)根據(jù)傳入?yún)?shù)的順序自動(dòng)排列。
在 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
。
#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ù)。
免責(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)容。