当前位置: 首页 > news >正文

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

文章目录

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

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.14159cout << format("Fixed:{:.2f}\n", val); // 固定2位小数 3.14cout << format("Scientific:{:.2e}\n", val);//科学计数法 3.14e+00return 0;
}

字符串格式化

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

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


http://www.mrgr.cn/news/49122.html

相关文章:

  • 【Redis】什么是Redis
  • RabbitMQ 入门(二)基本结构和消息模型
  • S4.2.6.1 LTSSM 之 Detect 状态
  • 【C++栈】2434. 使用机器人打印字典序最小的字符串|1953
  • MySQL 删除数据库
  • python 画图|三维散点图输出
  • 现代数字信号处理I-P2概率论学习笔记
  • 基于51单片机的超市商场电子秤MPX4115proteus仿真
  • 基于Java的旅游网站管理系统—计算机毕业设计源码39235
  • LeetCode题练习与总结:区域和检索 - 数组不可变--303
  • 【畅捷通好生意-注册安全分析报告-无验证方式导致安全隐患】
  • 利用AI工具快速帮助自己升级知识体系,同时保持警惕不要过度依赖
  • JAVA学习-练习试用Java实现“括号生成”
  • YOLO11改进|注意力机制篇|引入注意力机制Shuffle Attention
  • ubuntu20.4环境下gcc-aarch64交叉编译器的安装
  • 【SOP】迭代管理-checkList模版
  • 跨域问题及解决方案详解:同源策略与CORS机制
  • python 画同心圆/棋盘
  • FLASK 数据库建立以及部署和表的创建
  • 了解Python 中的 __class__ 属性