c++20 format基本使用

发布时间 2023-08-14 22:01:27作者: yuzuki_n

下面代码是一个使用format的例子

#include <iostream>
#include <cmath>
#include <format>

int main()
{
    double principal{ 1000 };
    double rate{ 0.5 };

    std::cout << std::format("Initial principal: {:>7.2f}\n", principal);
    std::cout << std::format(" Interest rate: {:>7.2f}\n", rate);

    std::cout << std::format("\n{}{:>20}\n", "Year", "Amount on deposit");

    for (int year{1}; year <= 10; ++year)
    {
        double amount = principal * pow(1.0 + rate, year);
        std::cout << std::format("{:>4d}{:>20.2f}\n", year, amount);
    }
}

这个例子里面,例如下面这一句
std::cout << std::format("{:>4d}{:>20.2f}\n", year, amount);
{}是占位符,将会被后面的year替代,代表我要使用格式说明符(format specifier), >4d表示说,向右的箭头代表右对齐,4代表占4个宽度,d代表室一个decimal类型,其他的以此类推