I've been having trouble with reading to a two-dimensional array of strings in C. I have a text file with a layout of: Name, Number of hobbies(H), Name of Hobbies. So the array is determined by the number of hobbies.
#include <stdio.h>
#include <string.h>
typedef struct{
char name[10];
int H;
char hobbi[20];
} data;
int main(void) {
data person[50];
FILE *input;
char source[]=("data.txt");
inout=fopen(source,"r");
int i=0;
int j;
while(!feof(input)) {
fscanf(input, "%s", person[i].name);
fscanf(input, "%d", person[i].H);
for(j=0; j<=person[i].H; j++){
fscanf(input, "%s", person[i].hobbi[j]);
}
i++;
}
fclose(input);
getchar();
getchar();
return 0;
}
And I have a .txt file as follow:
Jason 3 basketball bowling cycling
Arnold 2 boxing rollerskating
Mary 2 basketball rollerskating
Anne 3 bowling boxing basketball
The goal of the program is that when you input a name of a hobbie it gives you a list of names, that have that hobbie in common. But first, I'm trying to get the input part right. I translated the part of code to English so I hope there aren't any mistakes that wreck the code. Any help is much appreciated :)
%MAX_LENs, for example:fscanf(input, %9s, person[i].name). If you don't, then you could overwrite information outside ofperson's block. Always remember to leave 1 extra space for the 0 at the end of strings (why we use%9sfor achar[10])