0

How can we use %n in sscanf in C

Below is the example, but it shows incorrect result in numpassed.

#include <stdio.h>

int main(void)
{
char str[] = "156987139xyz";
int conv1 = 0;
int conv2 = 0;
int conv3 = 0;
int numpassed = 0;

sscanf(str, "%2X %3X %3X %n", &conv1, &conv2, &conv3, &numpassed);
printf("conv1 = %X, conv2 = %X, conv3 = %X, numpassed = %i\n",
        conv1, conv2, conv3, numpassed);
return 0;
}

This is my result conv1 = 15, conv2 = 698, conv3 = 713, numpassed = 5

can anyone please help me here

nisha
  • 69
  • 1
  • 7
  • 1
    I get a result of `8`. Sounds about right to me, seeing as we're taking `2`, then `3`, and then `3` again. Are you getting something else? – Blaze Mar 29 '19 at 10:20
  • 1
    I get `conv1 = 15, conv2 = 698, conv3 = 713, numpassed = 8`. Which compiler and OS do you use? – Bodo Mar 29 '19 at 10:20
  • Can you let me know what will be the result of below code sscanf(str, "%X %X %X %n", &conv1 , &conv2 , &conv3, &numpassed ); printf("conv1 = %X, conv2 = %X, conv3 = %X, numpassed = %i\n", conv1, conversion2, conversion3, numpassed ); – nisha Mar 29 '19 at 10:51
  • in response to previous comment. numpassed will change to 9 wouldn't it ?---as it would read the next character in str as an integer. Related usage: https://stackoverflow.com/questions/13199693/what-does-the-n-stand-for-in-sscanfs-d-n-i-n and https://en.cppreference.com/w/c/io/fscanf – pm101 Mar 29 '19 at 11:11
  • @pm101 %n refers to number of chars read so far. it will reflect 8. – DTdev Mar 29 '19 at 11:20
  • is your output changing numpassed = %i\n to numpassed = %d\n in printf() ? – DTdev Mar 29 '19 at 11:22
  • oh I thought it had changed from %n to %i in scanf , my bad – pm101 Mar 29 '19 at 11:37

0 Answers0