0

problem with scanning part of an struct, using pointer and malloc

#include <stdio.h>
#include <stdlib.h>
struct evento{
    char nome [100];
    char local [100];
    int dia;
    int mos;
    int anos;
};
int main (){
    int i,n;
    i=0;
    scanf ("%d",&n);
    struct evento *agenda;
    agenda =(struct evento*) malloc(n*sizeof(struct evento));
    for (i=0;i<n;i++){
        fgets (agenda[i].nome,100,stdin);
        fgets (agenda[i].local,100,stdin);
        scanf ("%d",&agenda[i].dia);
        scanf ("%d",&agenda[i].mos);
        scanf ("%d",&agenda[i].anos);
    }
    printf ("happy day");
    free(agenda);
    return 0;
}

When I put the value of n and the two strings, the program will printf the quote and not let me put the value of neither dia, mos or anos.

so if I put something like 1 (value of n), name and event, the program will finish and printf the quote, instead of letting me put the other values. why???

  • When mixing scanf and fgets you need to be aware of the line feed characters. fgets reads the line feed but puts it with the data. scanf however leaves the line feed in stdin. So at the first loop if you enter "hello" enter "world" enter "1" enter "2" enter "3" enter. Then you will read `"hello\n"`, ""`world\n"`, `1` `2` `3` but there will be trailing line feeds from scanf for the next lap of the loop. You need to 1) discard line feed characters read by fgets into the strings and 2) ensure to get rid of lf characters left behing by scanf - by for example adding an empty getchar() after each. – Lundin May 31 '23 at 06:54
  • And as you can tell stdio.h is a very strange, flawed and cumbersome library to work with. In fact it is almost certainly the worst library ever written for any programming language, all categories. So I wouldn't spent a great deal of energy learning it, since it isn't used in professional production code nowadays. – Lundin May 31 '23 at 06:57

0 Answers0