温馨提示×

std::format在c++中的使用示例有哪些

c++
小樊
83
2024-08-11 05:21:35
栏目: 编程语言

在C++20中引入了std::format作为新的格式化字符串工具,它可以替代传统的printf和stringstream等方式来进行字符串格式化。以下是std::format的一些使用示例:

  1. 基本用法:
#include <format>
#include <iostream>

int main() {
    std::string formatted = std::format("Hello, {}!", "world");
    std::cout << formatted << '\n';

    return 0;
}
  1. 格式化多个参数:
#include <format>
#include <iostream>

int main() {
    std::string formatted = std::format("The average of {} and {} is {}", 5, 10, (5+10)/2);
    std::cout << formatted << '\n';

    return 0;
}
  1. 使用格式说明符:
#include <format>
#include <iostream>

int main() {
    std::string formatted = std::format("The value is {:05}", 42);
    std::cout << formatted << '\n';

    return 0;
}
  1. 自定义格式化函数:
#include <format>
#include <iostream>

struct Point {
    int x;
    int y;
};

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

int main() {
    Point p = {3, 4};
    std::string formatted = std::format("Point coordinates: {}", p);
    std::cout << formatted << '\n';

    return 0;
}
  1. 使用自定义格式化标志:
#include <format>
#include <iostream>

int main() {
    std::string formatted = std::format("The number in binary is {:#b}", 42);
    std::cout << formatted << '\n';

    return 0;
}

这些示例展示了std::format的一些基本用法,包括基本用法、格式化多个参数、使用格式说明符、自定义格式化函数和使用自定义格式化标志等功能。通过std::format,可以更方便地进行字符串格式化操作。

0