Im trying to get input from the user for strings in a struct. However, when trying to get the input using scanf, apparently two of the strings get stored in the first character array of the struct. The input for the strings is given separated by spaces. Thats why Im trying to do it with scanf as I dont know if its possible to get input separated by spaces using fgets.

I have also tried changing the struct members to pointers to the character arrays and allocating memory for the strings using malloc, but kept getting seg fault after input.

#define MAXID 6
#define LAST_NAME_LENGTH   20

struct student
    char ID[MAXID];
    char f_name[FIRST_NAME_LENGTH];
    char s_name[LAST_NAME_LENGTH];
    int points[MAXROUNDS];

struct student studentinfo;


void student_info(struct student *studentinfo)
    printf("Give the students ID, surname and firstname.\n");
    scanf("%s%s%s", studentinfo->ID, studentinfo->s_name, studentinfo->f_name);

printf("Info of the last student added: %s %s %s\n", studentinfo.ID, studentinfo.s_name, studentinfo.f_name);

So with the input "666666 boi bobby" the output is "666666bobby boi bobby". What do?

1 Answers

bruno On Best Solutions

ID size if 6 but you enter 6 characters for it, there is no place for the null ending char which was saved into the first character of f_name before to be erased by the 'b' of bobby, so when you print ID there is no null character in it so the print continues writing the content of f_name producing 666666bobby then s_name is print producing boi then f_name is print (again) producing bobby

Enter 66666 rather than 666666 or increase the size of ID and that behavior disappear

This is why a protection must be used to avoid overflow when you read string with scanf