rlhh
rlhh

Reputation: 903

Scanning a String for strings

I'm trying to write a function that reads in a line from a file using fgets(). After reading the line, I want to take the line apart and make it into smaller strings. Depending on the first word in the line, the line that I read in can have 3-5 smaller strings that are separated by a white space.

Example: Line: remove apple 12345 string1: remove string2: apple string3: 12345

Line: add tomato red leaf string1: add string2: tomato string3: red string4: leaf

From the example above, if 1st string is remove, I need to read 2 other strings (apple, 12345). If the first string is add, I need to read 3 other strings (tomato, red, leaf).

Is there anyway that I can decide the number of times to read and do this using sscanf?

while( fgets( buf, sizeof buf, course_file ) != NULL ){
    sscanf( buf, "%s", &string1);
    printf( "%s\n", buf );
} 

It is not compulsory that I use sscanf, I'm open to other suggestions.

Upvotes: 1

Views: 161

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

The function typically used to tokenize strings is strtok, but it is not thread-safe; its modern version is strtok_r should be used instead.

Start tokenizing the buf in the first call, check the first token, and then go into one of several loops that depend on the content of the first token:

while( fgets( buf, sizeof buf, course_file ) != NULL ) {
    char *saveptr;
    char *tok = strtok_r(buf, " ", &saveptr);
    if (!strcmp(tok, "delete")) {
        for (int i = 0 ; i != 3 ; i++) {
            tok = strtok_r(NULL, " ", &saveptr);
            // Do something with the token...
        }
    } else if (!strcmp(tok, "add")) {
        for (int i = 0 ; i != 4 ; i++) {
            tok = strtok_r(NULL, " ", &saveptr);
            // Do something else with the token...
        }
    } else {
        // Error
    }
}

Upvotes: 2

Related Questions