Search code examples
cscanfstdio

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.


Solution

  • 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.