0

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 :)

1
  • %s can be very dangerous. You should always specify a maximum length with %MAX_LENs, for example: fscanf(input, %9s, person[i].name). If you don't, then you could overwrite information outside of person's block. Always remember to leave 1 extra space for the 0 at the end of strings (why we use %9s for a char[10]) Commented Feb 23, 2013 at 19:30

1 Answer 1

1

Your example shows "basketball bowling cycling" which is a string of more than 20 chars. I assume that each word should be stored separately, so for Jason, hobbi[0] = "basketball", hobbi[1] = "bowling". But hobbi only holds 20 chars. I think you need it to hold 20 strings of chars. Right now, hobbi[0] = 'b', hobbi[1] = 'a', hobbi[2] = 's', hobbi[3] = 'k', hobbi[4] = 'e', hobbi[5] = 't'.

You need to make hobbi an array of pointers. And allocate new space for each one.

char *hobbi[20];
...
fscanf(input, "%s", buffer);
person[i].hobbi[j] = strdup(buffer);

Or make it an array of arrays.

char hobbi[20][20];

With both of these, person[i].hobbi[j] is a string (eg., "basketball") and person[i].hobbi[j][k] is a char (eg., 'b').

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. I believe I should use the second option since we haven't covered strdub in school yet. I still have trouble understanding what you mean by the difference between string and char (I'm very novice and English isn't my first language) Can you give me an exapmle or something more to go on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.