0
#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 !

  • put a leading space in your 2nd `scanf` line to consume/ignore whitespace left in the buffer from the previous `scanf` call: `scanf(" %[^\n]",boxes[i].name);` See https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer – yano Dec 12 '22 at 23:10
  • 1
    `scanf` can be a royal pain for reading interactive input, despite its reputation as the "easy way" to read interactive input. See [this list of caveats and guidelines](https://stackoverflow.com/questions/72178518#72178652). As you've just discovered: `%[…]` is not your friend. – Steve Summit Dec 12 '22 at 23:16
  • @Kiriyama Rei, given input trouble, why does code not check the return value of `scanf()`? – chux - Reinstate Monica Dec 13 '22 at 01:09
  • 1
    @yano Suggesting `scanf(" %[^\n]",boxes[i].name)` without a _width_ is as bad as suggesting `gets()`. Use a width like `scanf(" %49[^\n]",boxes[i].name)` – chux - Reinstate Monica Dec 13 '22 at 01:11
  • @K Using `fgets()` does solve the problem if `scanf()` is not used anywhere. – chux - Reinstate Monica Dec 13 '22 at 01:12

0 Answers0