C++中格式化字符串一直都比较的繁琐,C++20提供了format用于优化这一过程。
#include <format>
#include <iostream>
using namespace std;
int main()
{
cout<<format("hello {}, and {}\n", "world", 88);
cout<<format("hello {1}, and {0}\n", 88, "world");
return 0;
}
format的第一个参数为字符串模板,跟printf的第一个参数类似。
其中{}用于占位符,类似于printf中的%d,%s。
{}中如果未指明索引,则从后续的参数列表中依次读取参数。
因此format("hello {}, and {}\n", "world", 88)格式化返回的字符串是:hello world, and 88
{}中如果指明了位置的索引(从0开始),则从后续参数所对应的位置读取参数
因此format("hello {1}, and {0}\n", 88, "world")格式化返回的字符串是:hello world, and 88
需要注意的是不能混合使用无位置的{}与有位置的{index}
1.控制格式化输出的形式