pradipta
pradipta

Reputation: 1744

parsing using sscanf not working

Need to get the value parsing using sscanf .. used as bellow but not getting the result..

String : abc_2_4 I need to get 4

My program

  char sentence []="abc_1_2";
  char str [20];
  int i,j;

  sscanf (sentence,"%s_%d_%d",str,&i,&j);
  printf ("%s  %d %d\n",str,i,j);

Output

abc_1_2 32768 134520820

My doubt can we use a non-white space char '_' in the string to be parsed by sscanf .

Please give me some idea.

Upvotes: 0

Views: 1106

Answers (2)

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25915

sscanf expects the %s tokens to be whitespace delimited . But here you have no space between abc and _ . So it will count _ also.

So in your case str will contain whole string abc_1_2 and i and j have garbage values.

To neglect _ you can try something like this.

  sscanf (sentence,"%[^_]_%d_%d",str,&i,&j);

Upvotes: 2

unwind
unwind

Reputation: 400159

sscanf() won't "look ahead" when parsing the %s to know that it should end with the underscore, that's not what the %s conversion specifier means.

You need to use %[^_] to capture all characters except underscore.

Upvotes: 3

Related Questions