gpt4 book ai didi

c - 在格式化输出函数中使用 $

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:03 25 4
gpt4 key购买 nike

我正在浏览 printf 的手册页函数,我遇到了一个解释在格式字符串中使用 $ 的语句(我实际上不太理解)。然后我试图为此寻找一些示例,但我找不到可以解释其在函数中的用法的好的示例。

谁能提供一个简单的例子来解释 $ 在任何格式化输出函数中的用法?

最佳答案

$ 格式的动机是,有时当您将数字插入翻译后的字符串时,插入的顺序会随着语言的变化而变化。为了能够只使用翻译后的格式字符串而不必知道值的顺序,格式字符串本身必须标记插入顺序:

// Simplified example, with thanks to Google translate for the azerbaijani.

const char* buy_book[NL] = {
[fmt_en] = "You can buy %d books for %d dollars.\n",
[fmt_az] = "Siz %2$d dollar %1$d kitab ala bil\u0259rsiniz.\n",
// ...
};

void bookoffer(enum Lang variant, int books, int dollars) {
printf(buy_book[variant], books, dollars);
}

偶尔重复格式化值是有用的; $ 可以让您不必提供两次值:

printf("The value at offset %1$d (0x%1$X) is %2$d (0x%2$X)\n", addr, value);

您还可以使用 $ 值来指定为 * 的精度:

printf("The first %1$d characters of the string are '%2$.*1$s'.\n",
nchar, str);

关于c - 在格式化输出函数中使用 $,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com