Search code examples
cstringstring-parsingscanf

sscanf() not properly parsing the input line


I'm writing a method to parse a string in a specific format, "55555;fhihehj;"

I have used sscanf in the past to do something similar, so I thought why not.

Here is my current code.

char toBreak[] = "55555;fjfjfhhj;";  
char* strNum = malloc(256); //256 * sizeof(char) = 256  
char* name = malloc(256);  
if (sscanf(toBreak, "%[^;];%[^;];", strNum, name)!=2)   
     return -1;
printf("%s, %s\n", strNum, name);

For some reason, it isn't parsing the string correctly and I am not sure why.


Solution

  • Taking your compilable code and making it into an SSCCE (Short, Self-Contained, Correct Example) gives us:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        char toBreak[] = "55555;fjfjfhhj;";
        char *strNum = malloc(256);
        char *name = malloc(256);
        if (sscanf(toBreak, "%255[^;];%255[^;];", strNum, name) != 2)
            return -1;
        printf("%s, %s\n", strNum, name);
        return 0;
    }
    

    I added the 255 to prevent buffer overflows in the general case where the input is not a constant in the program. Here, of course, the 256 byte allocations are very much larger than necessary, and overflow is not a problem. Note the 'off-by-one' on the length; the length in the format does not include the null byte, but there must be space for the null byte.

    When compiled and run on Mac OS X 10.9 Mavericks with GCC 4.8.2, that gives:

    55555, fjfjfhhj
    

    What platform are you running on — o/s and compiler? What do you get with the code I show?