Thread: sscanf & whitespaces

  1. #1
    Registered User
    Join Date
    Feb 2005

    sscanf & whitespaces

    I have a couple of strings that are formatted like this :
    "string1" "string2" "string3"

    eg :
    "testing" "hi_there" "56"

    I want to break up this string into 3 strings so I call this :

    char *input = "\"testing\" \"hi_there\" \"56\"";
    char score[16];
    char name[64];
    char value[16];
    sscanf(input, "%s %s %s", score, name, value);
    printf("%s %s %s\n", score, name, value);
    The output is :
    "testing" "hi_there" "56"

    So far so good. I get a problem though when I have a string like this :
    "testing" "I contain whitespaces" "56"

    The output is wrong then. I also understand why. But I can't find a way to get the string between the 2 ' " 's WITH whitespaces.

    Thanks in advance.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    If you don't need to include the double-quotes within the destination string, I'd say go with something like this.
    #include <stdio.h>
    int main()
       const char input[] = "\"testing\" \"I contain whitespaces\" \"56\"";
       char score[16];
       char name[64];
       char value[16];
       if ( sscanf(input, "\"%15[^\"]\" \"%63[^\"]\" \"%15[^\"]\"", 
                   score, name, value)  == 3 )
          printf("\"%s\" \"%s\" \"%s\"\n", score, name, value);
       return 0;
    /* my output
    "testing" "I contain whitespaces" "56"
    If you do need the double-quotes, I'd say write your own parsing function based on strchr or similar.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. whitespaces
    By happyclown in forum C Programming
    Replies: 2
    Last Post: 01-06-2009, 10:33 PM
  2. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  3. An equivalent of sscanf
    By g4j31a5 in forum C++ Programming
    Replies: 5
    Last Post: 07-04-2007, 01:27 AM
  4. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM
  5. sscanf (I think)
    By RyeDunn in forum C Programming
    Replies: 7
    Last Post: 07-31-2002, 08:46 AM