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

文章目录

  • [1. 使用C++20 std::format](#1. 使用C++20 std::format)
  • [2. 基本用法](#2. 基本用法)
  • [3. 格式说明](#3. 格式说明)

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

需要将VisualStudio默认的标准修改为C++20

菜单"项目"-"项目属性",打开如下对话框

代码中加入头文件

2. 基本用法

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

cpp 复制代码
#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. 格式说明

详细可查阅手册

整数格式化

cpp 复制代码
#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;
}

浮点数格式化

cpp 复制代码
#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;
}

字符串格式化

cpp 复制代码
#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}:表示浮点数使用科学计数法输出,保留两位小数。

相关推荐
GIS 数据栈2 分钟前
【Seggis遥感系统升级】用C++高性能服务Drogon重构软件服务架构|QPS提升300%,性能再升级!
java·开发语言·c++·重构·架构
王老师青少年编程15 分钟前
信奥赛C++提高组csp-s之二分图
数据结构·c++·二分图·csp·信奥赛·csp-s·提高组
柏木乃一17 分钟前
进程(11)进程替换函数详解
linux·服务器·c++·操作系统·exec
Q741_14717 分钟前
C++ 队列 宽度优先搜索 BFS 力扣 429. N 叉树的层序遍历 C++ 每日一题
c++·算法·leetcode·bfs·宽度优先
CSDN_RTKLIB19 分钟前
CMake成果打包
c++
Yu_Lijing28 分钟前
基于C++的《Head First设计模式》笔记——工厂模式
c++·笔记·设计模式
十五年专注C++开发31 分钟前
CMake进阶:核心命令get_filename_component 完全详解
开发语言·c++·cmake·跨平台编译
mrcrack39 分钟前
洛谷 B3656 【模板】双端队列 1 方案1+离线处理+一维数组+偏移量 方案2+stl list
c++·list
lingzhilab41 分钟前
零知IDE——基于STMF103RBT6结合PAJ7620U2手势控制192位WS2812 RGB立方体矩阵
c++·stm32·矩阵
go_bai42 分钟前
生产消费模型-简洁线程池
linux·c++·笔记