1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Rep Power

    Using sscanf for tabs in c

    i have a line like this "1\t10\tfirst test\t/app1/test" with tabs as delim.
    i am trying to parse using scanf and store in variables.
    i am using below.

    sscanf(line, "%d\t%d\t%[^\t]%[^\n]", &slno, &testid, tname, tcmd);

    and when i try to print those variables slno and testid are getting displayed correctly but string tname and tcmd are showing as (null).

    Can you specify the correct sscanf in c?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    It seems OK here
    #include <stdio.h>
    int main(void)
      char line[] = "1\t10\tfirst test\t/app1/test";
      int slno = 0, testid = 0;
      char tname[20] = { 0 }, tcmd[20] = { 0 };
      int res = sscanf(line, "%d\t%d\t%[^\t]%[^\n]", &slno, &testid, tname, tcmd);
      printf("Res=%d\n", res );
      printf("-%d- -%d- -%s- -%s-\n", slno, testid, tname, tcmd );
      return 0;
    $ gcc baz.c
    $ ./a.out 
    -1- -10- -first test- -	/app1/test-
    tcmd gets a leading tab, is that the problem?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo