c - printf() 精度

标签 c printf format-string

char buf[10];
int counter, x = 0;
snprintf (buf, sizeof buf , "%.100d%n", x, &counter); 
printf("Counter: %d\n", counter)

我正在学习 printf 的精度。使用 %.100d%n 时,这里的精度给出了 100 个数字来渲染 x。

我不明白的是为什么计数器会增加到 100,尽管实际上只有 10 个字符被写入缓冲区?

最佳答案

写入buf的十个字节为9个空格和1个'\0'(零终止符),counter赋值100 表示 99 个空格和 1 个 '0'(数字零)。

   buf <== "         "
%.100d <== "          .....   0"

请注意 buf 是不完整的:它没有 '0'

关于c - printf() 精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55005394/

相关文章:

c - 为什么 gcc -Wformat 不对 unsigned int 上的 printf %d 发出警告?

c - 是否可以检测程序是否已通过/proc/self/mem 动态链接?

c - 错误 "assignment makes integer from pointer without a cast array = NULL"

c - 将数组传递给 scanf 函数将不起作用

C 如何在没有编译器警告的情况下将地址打印为十进制值(不是十六进制)

c - 如何允许使用 scanf 输入空格?

c - 为什么在 fopen() 中使用无效模式时 gcc 不给出警告或错误?

c - scanf 不在 while 循环中等待用户输入

ios - onFormat string For NSPredicate

c - 写入以空字节开头的内存