没有正确计算到目前为止写入的字符数

not correctly counting the number of characters wrriten so far

据我所知,使用 %n = "相关的参数是一个指向整数的指针,到目前为止写入的字符数被放入其中。 我正在使用 win 8,codeblocks IDE。我尝试了一个应该打印至少 15 个字符的程序。但它只显示8。我什至重新启动了程序,但结果是一样的。

我也是从命令行编译的。

代码片段如下。

已上传结果快照。

首先是随机数。

#include<stdio.h>
 int main(void)
  {
   int i;
   printf("%d %f \n%n",100, 123.23, &i);
   printf("%d characters is so far.",i);
   return 0;
 }

[编辑 :: 在编辑问题后添加]

@Daniel 中所述,这看起来像是您的 OS 特定 C 库的特定问题。似乎不支持 %n 格式说明符。


不过,下面的答案还是有帮助的(恕我直言,这是必需的),所以保持原样。

我想,你误读了定义。它不计算 all 之前的调用,而是考虑同一调用的输出 only.

根据第 7.21.6.1 章,C11 标准,fprintf() 描述,第 8 段 [强调我的]

n

The argument shall be a pointer to signed integer into which is written the number of characters written to the output stream so far by this call to fprintf. No argument is converted, but one is consumed. If the conversion specification includes any flags, a field width, or a precision, the behavior is undefined.

这个问题是 Windows 特有的,它源于 Windows' C 库出于安全原因禁用了 %n 说明符这一事实。

要绕过它,请转到 Settings -> Compiler,然后在 Global Compiler Settings 中转到 Other options 并添加 -D__USE_MINGW_ANSI_STDIO。这将启用 %n 说明符。