#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[50];
}box;
void fill_boxes(box *boxes, int length)
{
for (int i = 0; i < length; i++) {
printf("Enter box %d id: ", i+1);
scanf("%d",&boxes[i].id);
printf("Enter box %d name: ", i+1);
/* scanf("%s",boxes[i].name); */
scanf("%[^\n]",boxes[i].name);
}
}
void print_elements(box *boxes, int length)
{
for (int i = 0; i < length; i++) {
printf("\nbox %d \n\tid = %d\n\tname = %s",i+1,boxes[i].id, boxes[i].name);
}
printf("\n");
};
int main()
{
box *boxes = malloc(2 * sizeof(box));
fill_boxes(boxes, 2);
print_elements(boxes, 2);
free(boxes);
return 0;
}
I tried using scanf("%s",boxes[i].name) but it only accepts one word and using fgets does not solve the problem either. Actually it's a recurrent problem with my c programs so I'm surely missing some theory !