C++基础补充(03)C++20 的 std::format 函数

1. 使用C++20 std::format

需要将VisualStudio默认的标准修改为C++20
菜单“项目”-“项目属性”,打开如下对话框
在这里插入图片描述
代码中加入头文件

2. 基本用法

通过占位符{}制定格式化的位置,后面传入变量

#include<iostream>
#include<format>
#include<string>
using namespace std;

int main()
{
	int x = 68;
	double pi = 3.14159;
	string name = "Alice";

	//格式化字符串
	string rst = format("Hello,{}! The answer is {} and pi is {:.2f}.", name, x, pi);

	cout << rst << endl;

	return 0;
}

输出
Hello,Alice! The answer is 68 and pi is 3.14.

使用 {} 作为占位符,参数顺序插入
可以指定格式。{:.2f} 表示保留2位小数

3. 格式说明

详细可查阅手册
整数格式化

#include<iostream>
#include<format>
#include<string>
using namespace std;

int main()
{
	int x = 68;
	cout << format("Decimal:{}\n", x);//十进制输出
	cout << format("Hex:{:#x}\n", x);//十六进制输出
	cout << format("Binary:{:#b}\n", x);//二进制输出
	return 0;
}

浮点数格式化

#include<iostream>
#include<format>
#include<string>
using namespace std;

int main()
{
	double val = 3.14159;
	cout << format("Default: {}\n", val);  // 默认 3.14159
	cout << format("Fixed:{:.2f}\n", val); // 固定2位小数 3.14
	cout << format("Scientific:{:.2e}\n", val);//科学计数法 3.14e+00
	return 0;
}

字符串格式化

#include <iostream>
#include <format>
using namespace std;
int main() 
{
    string str = "Hello";
    cout << format("Default: {}\n", str);    // 默认输出: Hello
    cout << format("Padded: {:>10}\n", str); // 右对齐,宽度 10:      Hello
    cout << format("Left Padded: {:<10}\n", str);  // 左对齐,宽度 10: Hello     
    return 0;
}

输出
在这里插入图片描述
{:#x}:表示带有前缀的十六进制输出,前缀为 0x。
{:#b}:表示带有前缀的二进制输出,前缀为 0b。
{:05}:表示使用 5 位宽度输出,并用零进行左侧填充。
{:.2f}:表示浮点数保留两位小数。
{:.2e}:表示浮点数使用科学计数法输出,保留两位小数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dotdotyy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值