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.
The problem is in the way you are using
strtok()
. From the manpage:That means to parse
str
, you have to first call it asstrtok(str, " ")
, and to further parse the string, you have to call it asstrtok(NULL, " ")
. When you call it asstrtok(str, " ")
the second time, it starts again from the beginning ofstr
.