C 转换说明符

标签 c printf

我对编程比较陌生,目前正在学校学习 C。我在学习时遇到了一个问题,但很难在网上找到答案,所以我决定问自己的问题。

转换说明符中%后面的整数是什么意思?

例如,我注意到 %s 有时会写成 %5s 或 %-8s。

我知道这与间距有关,并且自己也进行了一些实验,但我似乎在精确定位整数的功能方面遇到了一些麻烦。

非常感谢任何其他建议或提示。谢谢!

编辑:我做了一些研究和实验,发现数字与空格有关。例如:

#include <stdio.h>

int main(void)
{
    printf("%4d\n", 1);
    printf("%8d\n", 2);
}

将输出:

    1
        2

如果在转换说明符后面包含负整数,则意味着 printf 会将输出格式化为在输出后面包含空格。例如:

#include <stdio.h>

int main(void)
{
    printf("%-4d%d", 1, 2);
}

将输出

1    2

我希望这可以帮助任何刚接触格式化输出并感到困惑的人。

最佳答案

来自 C 标准(7.21.6.1 fprintf 函数)

4 每个转换规范均由字符 % 引入。在%之后,依次出现以下内容:

...

— An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer

以及进一步

5 As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.

最后

6 The flag characters and their meanings are:

  • The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)

关于C 转换说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107175/

相关文章:

c - Loop后输出错误是strcat引起的?

c - 单个 printf 语句如何更改数组中的值?

c - 我的do-while循环有问题,但不确定是什么问题(C语言)

c - C 中的二叉搜索树。程序无法正常工作。

c - 从函数返回一个值

c - 识别文本中的空格

c - 打印从包含特定单词的文件中读取的一行

c - 为什么会有无限循环?

c++ - printf 中 C++ 客户端/服务器应用程序的段错误

c - 使用 fgets() 和 echo 用 C system() 调用封装单行 AppleScript