herzl shemuelian
herzl shemuelian

Reputation: 3508

How to set sscanf() to ignore characters at start of string?

I have a string as below

 char row[]="11/12/1999 foo:bar some data..... ms:12123343 hot:32";

I want insert 'ms' val to int variable by using sscanf. But I don't know how to configure ssscanf to ignore first data in row. I try blow but don't do the job.

int i;
sscanf(row,".*ms:%d",i);

Upvotes: 3

Views: 10722

Answers (2)

pmg
pmg

Reputation: 108938

I think, rather than using sscanf() to ignore data, your best bet is to use another function to get the part of the string you want.

I suggest strstr(). For example

#include <stdio.h>
#include <string.h>

int main(void) {
    char row[] = "11/12/1999 foo:54654 some data..... ms:12123343 hot:32";
    char *ms;
    int i;

    ms = strstr(row, "ms:");
    if (ms == NULL) /* error: no "ms:" in row */;
    if (sscanf(ms + 3, "%d", &i) != 1) /* error: invalid data */;
    printf("ms value is %d.\n", i);
    return 0;
}

You can see the code running at ideone.

Upvotes: 5

md5
md5

Reputation: 23699

The joker is used in shells, but sscanf does not treat the * character this way.

7.21.6.2 The fscanf function
— An optional assignment-suppressing character *.

There are several solutions. For example:

#include <stdio.h>
#include <string.h>

char *pend = strrchr(row, ':');
sscanf(pend, ":%d", &i);

You can also use scanset from scanf or strstr.

Upvotes: 0

Related Questions