C++20 引入了 std::format,這是一個(gè)現(xiàn)代化、類(lèi)型安全且高效的格式化庫(kù),用于替代傳統(tǒng)的 printf
和繁瑣的 std::ostringstream
操作。它借鑒了 Python 的字符串格式化語(yǔ)法,使用起來(lái)更直觀、更安全。
#include <format>
g++ -std=c++20 -fconcepts -O2 main.cpp
std::format 返回一個(gè)格式化后的字符串,而 std::print 直接輸出到控制臺(tái)(C++23 才正式加入,目前部分實(shí)現(xiàn)可用)。
立即學(xué)習(xí)“C++免費(fèi)學(xué)習(xí)筆記(深入)”;
示例:基本格式化
#include <format><br>#include <iostream><br><br>int main() {<br> std::string name = "Alice";<br> int age = 30;<br> double height = 1.68;<br><br> std::string msg = std::format("姓名: {}, 年齡: {}, 身高: {:.2f}m", name, age, height);<br> std::cout << msg << std::endl;<br> // 輸出: 姓名: Alice, 年齡: 30, 身高: 1.68m<br>}
占位符使用 {}
,可指定參數(shù)索引、類(lèi)型、寬度、精度、填充等。
std::format("{}, {}, {}", a, b, c)
std::format("{1}, {0}", "world", "hello") → "hello, world"
{name}
這樣的命名參數(shù)格式說(shuō)明符結(jié)構(gòu):{[index]:[fill][align][width][.precision][type]}
常見(jiàn)格式類(lèi)型
{:d}
十進(jìn)制std::ostringstream
0 小寫(xiě)十六進(jìn)制std::ostringstream
1 大寫(xiě)十六進(jìn)制std::ostringstream
2 八進(jìn)制std::ostringstream
3 二進(jìn)制std::ostringstream
4 保留兩位小數(shù)std::ostringstream
5 科學(xué)計(jì)數(shù)法std::ostringstream
6 不顯示小數(shù)部分std::ostringstream
7 右對(duì)齊,寬度為8std::ostringstream
8 左對(duì)齊std::ostringstream
9 居中#include <format>
0 左補(bǔ)0,右對(duì)齊#include <format>
1 用 * 填充示例:格式控制
std::cout << std::format("|{:>8}|{:<8}|{:^8}|\n", "left", "right", "center");<br>// | left|right&&&| center |<br><br>std::cout << std::format("{:08x}", 255) << "\n"; // 000000ff<br>std::cout << std::format("{:.2f}", 3.14159) << "\n"; // 3.14
要讓自定義類(lèi)型支持 #include <format>
2,需特化 #include <format>
3。
示例:格式化日期結(jié)構(gòu)
struct Point {<br> double x, y;<br>};<br><br>template<><br>struct std::formatter<Point> {<br> constexpr auto parse(auto& ctx) {<br> return ctx.begin();<br> }<br><br> auto format(const Point& p, auto& ctx) const {<br> return std::format_to(ctx.out(), "({:.2f}, {:.2f})", p.x, p.y);<br> }<br>};<br><br>// 使用<br>Point p{1.234, 5.678};<br>std::cout << std::format("點(diǎn)坐標(biāo): {}", p) << "\n";<br>// 輸出: 點(diǎn)坐標(biāo): (1.23, 5.68)
parse 方法處理格式字符串(如支持 .2f),format 方法執(zhí)行實(shí)際格式化。
基本上就這些。std::format 讓 C++ 字符串格式化變得更簡(jiǎn)潔、更安全。雖然當(dāng)前工具鏈支持還在完善中,但它是未來(lái)標(biāo)準(zhǔn)方式,值得盡早掌握。
以上就是c++++中如何格式化輸出_C++20 std::format格式化庫(kù)使用指南的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
c++怎么學(xué)習(xí)?c++怎么入門(mén)?c++在哪學(xué)?c++怎么學(xué)才快?不用擔(dān)心,這里為大家提供了c++速學(xué)教程(入門(mén)到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)