luvAtime41
luvAtime41

Reputation: 47

How to parse a single word from a line of text with sscanf

For example, given this line of text from a file

Today: Wed @2p,@3p,5

How would I just get "@2p" using sscanf? Right now I am using this code:

char 1st[3];
char 2nd[3];
int num;

sscanf(str,"%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);
printf("1st = %s\n", 1st);
printf("2nd = %s\n", 2nd);
printf("num = %s\n", &num);

and the output is

1st = Wed
2nd = 'empty characters'
num = 'empty characters'Wed

What could I be doing wrong here?

Upvotes: 1

Views: 240

Answers (2)

chux
chux

Reputation: 153527

The below fails as "%*[^:]" scans "Today", then "%*[^\t]" scans in ":", "%s" scans in and does not save "\t", continues scanning and saves "Wed" into an array that is too small leading to undefined behavior.

sscanf("Today:\tWed @2p,@3p,5", "%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);

The below fails as "%*[^:]" scans "Today", then "%*[^\t]" scans in ": Wed @2p,@3p,5", leaving nothing for "%s". It also does not check the results of sscanf(). Always check the result to insure valid results.

sscanf("Today: Wed @2p,@3p,5", "%*[^:]%*[^\t]%s,%s,%d", 1st, 2nd, &num);

Further "@2p" cannot fit in a char [3] array. Need room for the null character.


Decide what constitutes acceptable characters: the scanset and the maximum number of characters. Check results

#define Word_Max 3
#define Prefix "%*[^@]"
#define ScanSet "%3[A-Za-z0-9@]"

char *str = "Today: Wed @2p,@3p,5";
char word[2][Word_Max + 1];
int num;

if (3 == sscanf(str, Prefix ScanSet "," ScanSet ",%d", word[0], word[1], &num)) {
  printf("'%s' '%s' %d\n", word[0], word[1], num);
} else {
  puts("Fail");
}

Output

'@2p' '@3p' 5

Upvotes: 1

nsilent22
nsilent22

Reputation: 2863

I guess your %*[^\t] "eats up" just the semicolon left by the %*[^:]. So:
%*[^:]% gets Today
*[^\t]% gets :
%s gets Wed
and since after Wed there is no comma, following %s get nothing

Following code will get you @2p in the char array:

sscanf(str, "%*[^@]%[^,]", 1st);

Upvotes: 0

Related Questions