1

I'm trying to read a string using sscanf() in a loop but the offset is zero. What is the correct way and is it possible at all to have track of the offset?

In the example here the offset should be 5 but the actual value is 0 and I had to set it manually to 5.

char line[35]=" -123    1  -25-1245  -12";
char *data=line;
char buf[6];
int offset;
int n,i;

for(i=0;i<5;i++){
  if(sscanf(data,"%5[^\n\t]s%n",buf,&offset)==1){
    n=atoi(buf);
    data+=5;//offset;
  printf("n= %5d  offset= %d\n",n, offset);
  }
 }

The result is:

n=  -123  offset= 0
n=     1  offset= 0
n=   -25  offset= 0
n= -1245  offset= 0
n=   -12  offset= 0
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
DudeNukem
  • 47
  • 6

2 Answers2

3

The problem is that a 'scan set' %[…] in sscanf() et al is a complete conversion specification, not a modifier for %s. Your data has no s characters in it, so the sscanf() fails on matching the literal s in your format string, and hence fails to set offset because the matching failed.

Use more white space and fewer s's:

char line[35] = " -123    1  -25-1245  -12";
char *data = line;
char buf[6];
int offset;
int n, i;

for (i = 0; i < 5; i++)
{
    if (sscanf(data, "%5[^\n\t]%n", buf, &offset) == 1)
    {
        n = atoi(buf);
        data += offset;
        printf("n = %5d; offset = %d\n", n, offset);
    }
}

Your question already shows that you know most of what's discussed in How to use sscanf() in loops?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • yes as @R.. already mentioned I was wrong in adding the s after the set specifier as I was storing the results from sscanf() into a string ... Obviously I have a bad C reference sources. – DudeNukem Sep 04 '19 at 14:39
  • 1
    It's a common mistake to assume that the scan set notation is a modifier for `%s`; there are numerous questions on SO where that's the problem. I originally thought it was going to be a simple question of "this is a duplicate of 'How to use `sscanf()` in loops'" but I realized the `s` was causing the trouble. If your sources conflate `%[…]` with `%s`, then you should look askance at the other information those sources provide — there are likely to be other problems. – Jonathan Leffler Sep 04 '19 at 14:43
2

You have a misplaced literal 's' in the middle of your sscanf conversion specification string, which likely does not match and causes sscanf to fail before even reaching the %n. Remove it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711