简体   繁体   中英

Getting the offset from sscanf while reading a string in a loop in C

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

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?

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.

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