温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解C++ format函数的格式化占位符

发布时间:2024-10-11 09:22:39 来源:亿速云 阅读:90 作者:小樊 栏目:编程语言

在 C++ 中,std::string 类有一个名为 format 的成员函数,它允许您使用类似于 Python 的格式化字符串语法来构造新字符串。format 函数的格式化占位符与 Python 的 str.format 和 C# 的 string.Format 类似,但具有其独特的语法。

以下是 C++ std::string 类中 format 函数的一些常见格式化占位符:

  1. %s - 字符串格式化占位符。将替换为传入的字符串参数。
std::string s = "Hello";
std::string result = std::string("Hello, %s!").format(s);
// result = "Hello, Hello!"
  1. %d - 整数格式化占位符(十进制)。将替换为传入的整数参数。
int i = 42;
std::string result = std::string("The answer is %d.").format(i);
// result = "The answer is 42."
  1. %f - 浮点数格式化占位符。将替换为传入的浮点数参数。默认情况下,小数点后保留 6 位数字。可以使用 .6f 来指定小数点后的位数。
double d = 3.1415926535;
std::string result = std::string("Pi is approximately %f.").format(d);
// result = "Pi is approximately 3.141593."
  1. %e - 科学计数法表示的浮点数格式化占位符。将替换为传入的浮点数参数,并以科学计数法表示。
double d = 1.23456789e-10;
std::string result = std::string("A very small number: %e").format(d);
// result = "A very small number: 1.234568e-10"
  1. %x - 十六进制表示的整数格式化占位符。将替换为传入的整数参数,并以十六进制表示。
int i = 255;
std::string result = std::string("The hexadecimal value of %x is %X").format(i, i);
// result = "The hexadecimal value of ff is FF"
  1. %o - 八进制表示的整数格式化占位符。将替换为传入的整数参数,并以八进制表示。
int i = 10;
std::string result = std::string("The octal value of %o is %O").format(i, i);
// result = "The octal value of 12 is 12"
  1. %c - 字符格式化占位符。将替换为传入的字符参数。
char c = 'A';
std::string result = std::string("The ASCII value of %c is %d.").format(c, static_cast<int>(c));
// result = "The ASCII value of A is 65."
  1. %n - 换行符格式化占位符。在字符串中插入一个换行符。
std::string result = std::string("Hello, %s!\n").format(s);
// result = "Hello, Hello!\n"

这些占位符可以组合使用,以创建更复杂的格式化字符串。例如:

int year = 2023;
int month = 10;
int day = 20;
std::string result = std::string("Today is %d/%02d/%02d.").format(day, month, year);
// result = "Today is 20/10/2023."

在这个例子中,%d 用于天,%02d 用于月份和年份(带有前导零,如果需要的话)。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI