Galc127 Galc127 - 2 months ago 7
C Question

Parsing a line from file

I have a file with the following line:

numOfItems = 100


I want to read the line from file and initialize the attribute "numOfItems" to 100. How could I do it, i.e, deleting the unnecessary spaces and read only the values I need?

Also, I have another line which is:

num Of Items = 100


which I need to parse as error (attributes and values cannot contain spaces).

In the first case I know how to remove the spaces at the beginning, but not the intervening spaces. In second case I don't know what to do.

I thought to use
strtok
, but couldn't manage to get what I needed.

Please help, thanks!

Answer

Using fgets and sscanf with %s %d and %n should parse lines of the format "item = value"

#include <stdio.h>
#include <string.h>

int main( void){
    char line[256] = { '\0'};
    char item[50] = { '\0'};
    int value = 0;
    int used = 0;

    printf ( "enter string as \"item = value\" or x to exit\n");
    while ( ( fgets ( line, 256, stdin))) {
        if ( strcmp ( line, "x\n") == 0) {
            break;
        }
        //%49s to prevent too many characters in item[50]
        //%n will report the number of characters processed by the scan
        //line[used] == '\n' will succeed if the integer is followed by a newline
        if ( ( ( sscanf ( line, "%49s = %d%n", item, &value, &used)) == 2) && line[used] == '\n') {
            printf ( "parsed item \"%s\" value \"%d\"\n", item, value);
        }
        else {
            printf ( "problem parsing \n\t%s\n", line);
        }
        printf ( "enter string as \"item = value\" or x to exit\n");
    }

    return 0;
}
Comments