Search code examples
cfgetsscanf

Read from line with sscanf, including whitespaces, breaking on other character


I'm sorry for the sloppy title, but I didn't know how to format my question correctly. I'm trying to read a .txt, of which every line has information needed to fill a struct. First I use fgets to read the line, and then i was going to use sscanf to read the individual parts. Now here is where I'm stuck: normally sscanf breaks off parts on whitespaces, but I need the whitespace to be included. I know that sscanf allows ignoring whitespaces, but the tricky part is that I then need some other arbitrary character to separate the parts. For example, I have to break the line

Carl Sagan~Contact~scifi~1997

up into parts for Author,Name,Genre,year. You can see I need the space in Carl Sagan, but I need the function to break off the strings on the tilde character. Any help is appreciated


Solution

  • If your input is delimited by ~ or for instance any specific character: Use this:

    sscanf(s, "%[^~]", name);
    

    [^ is conversion type, that matches all characters except the ones listed, ending with ]

    Here is the sample program for testing it:

    #include <stdio.h>
    
    int main(int argv, char **argc)
    {
        char *s = "Carl Sagan~Contact~scifi~1997";
        char name[100], contact[100], genre[100];
        int yr;
    
        sscanf(s, "%99[^~]~%99[^~]~%99[^~]~%d", name, contact, genre, &yr);
        printf("%s\n%s\n%s\n%d\n", name, contact, genre, yr);
    
        return 0;
    }