gpt4 book ai didi

c - %n 在 printf 中不工作

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:22 24 4
gpt4 key购买 nike

我有一个问题,printf 中的 %n 不起作用,我在 win7 上使用 Dev-Cpp 5.3.0.4

#include<stdio.h>
int main(void)
{
int n;
char *x;
gets(x);
printf("\n%s%n\n",x,&n);
printf("n: %d\n",n);
return 0;
}

输出:

hello how are you?

hello how are you?n: 2046

--------------------------------
Process exited with return value 0
Press any key to continue . . .

为什么?我该如何解决?提前致谢;)

最佳答案

查看 printf 联机帮助页:

   n      The  number of characters written so far is stored into the integer indicated by the int
* (or variant) pointer argument. No argument is converted.

因此,您必须传递一个指向 int 的指针。此外,正如 Xavier Holt 指出的那样,您必须使用有效的缓冲区才能读入。试试这个:

#include <stdio.h>
int main(void)
{
int n;
char x[1000];
fgets(x, 1000, stdin);
printf("\n%s%n\n",x,&n);
printf("n: %d\n",n);
return 0;
}

这段代码对我有用。

关于c - %n 在 printf 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041781/

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