简体   繁体   中英

%n not working in printf

I have a problem, %n in printf doesn't work, i'm using Dev-Cpp 5.3.0.4 on win7

#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;
}

output:

hello how are you?

hello how are you?n: 2046

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

why? how can i solve? thanks in advance ;)

Have a look at the printf manpage:

  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. 

So, you'll have to pass a pointer to an int. Also, as Xavier Holt pointed out, you'll have to use a valid buffer to read into. Try this:

#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;
}

This code works for me.

您需要将指针传递给n

n的参数必须是一个有符号int的指针,而不是一个单数int。

That's not how to use the "%n" specifier.

See the C99 Standard .

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.

Also you need some place to store the input (hint: initialize x )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM