Differentiating data in a file C

2019-09-11 05:14发布

I am trying to read the contents of a file which are sectioned into two separate types. This is shown below:

# Type names
bird
mammal
reptile
.
# Type effectiveness
Very_effective
Not_effective
.

So far I can read the contents of the first type, but when I try to read the contents of the second, I keep re-reading the contents of the first.

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

int main() {
    typedef struct 
    {
        char types[1000];
        char effectiveness[1000];
    } sinFile; 
    sinFile record[1000];

    FILE* file; 
    char line[121];
    char period[10];
    char hash[10];

    char* item; 
    char* item2;
    int i = 0;
    int j = 0;

    file = fopen("Test.txt", "r");

    while(fgets(line, 120, file)) {
        item = strtok(line, " ");
        strcpy(period, ".");

        if (item[0] == '#') {
            continue;
        } else {
            do {
                strcpy(record[i].types, line);
                i++;
            } while (strcmp(record[i].types, period) == 0);
        }
        item2 = strtok(line, " ");
        if (item2[0] == '#') {
            continue;
        } else {
            do {
                strcpy(record[j].effectiveness, line);
                j++;
            } while (strcmp(record[j].effectiveness, period)== 0);
        }
    }

    fclose(file);

    printf("%s", record[0].effectiveness);
}

At the moment when I try to print out the first effectiveness type, it prints out 'bird' etc.

I feel like I am close but I'm not sure as to how to procede.

1条回答
地球回转人心会变
2楼-- · 2019-09-11 05:20

The problem is in the way you are using strtok(). From the manpage:

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

That means to parse str, you have to first call it as strtok(str, " "), and to further parse the string, you have to call it as strtok(NULL, " "). When you call it as strtok(str, " ") the second time, it starts again from the beginning of str.

查看更多
登录 后发表回答