Search code examples
cfilescanfc-stringsfgets

Reading from file line by line and matching pattern - C


I have a text file with lines like this:

"string maybe contains more than one word - string as the previous - number"

I read from this file line by line with fgets, but the sscanf just cut off everything except the first string. How can I solve this problem?

char new_name[30], new_district[30], buffer[100];
unsigned new_part_count;
while(fgets(buffer, 100, file)) {
    sscanf(buffer, "%s - %s - %u", new_name, new_district, &new_part_count);
}

Solution

  • Try the following call

    sscanf( buffer, "%29[^-] - %29[^-] - %u", new_name, new_district, &new_part_count );
        
    

    If to use just the conversion specifier %s then any white space character terminates the input of a string.