⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

C++20 std::format:类型安全的字符串格式化

掌握std::format的语法、占位符、格式说明符,替代printf和iostream。 · 难度:入门 · +15XP

为什么需要std::format?

std::format提供了类似Python的格式化语法,类型安全、性能优异且可读性强。它定义在<format>头文件中。

基本用法

#include <format>
#include <iostream>

int main() { std::string msg = std::format("Hello, {}! You have {} messages.", "Alice", 42); std::cout << msg << ' '; }

格式说明符

占位符可以包含格式说明,例如宽度、精度、填充字符和对齐方式。

std::format("{:>10}", 42);      // "        42"
std::format("{:<10}", 42);      // "42        "
std::format("{:^10}", 42);      // "    42    "
std::format("{:.2f}", 3.14159); // "3.14"
std::format("{:#x}", 255);      // "0xff"

格式化选项表

说明符含义
{}默认格式
{:d}十进制整数
{:f}浮点数
{:s}字符串
{:06}宽度6,前导零

自定义类型格式化

可以特化std::formatter来支持自定义类型。

struct Point { int x, y; };

template<> struct std::formatter<Point> { constexpr auto parse(auto& ctx) { return ctx.begin(); } auto format(const Point& p, auto& ctx) { return std::format_to(ctx.out(), "({}, {})", p.x, p.y); } };

练习提示

编写一个程序,使用std::format输出一个对齐的表格,包含学生姓名、分数和等级。要求使用宽度和对齐说明符。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 105 篇
0 完成
🔥 0