Problem with input buffer -

4

I have a problem with a program in C. I want to create an array of data of type unc, previously created with struct. The program asks to enter data type string and int type. The program can be compiled but when I want to use the program the following happens:

  • I can enter what is saved in n a and e in the first position ( l[0] )

  • After writing an age to save in e of the first position, when pressing enter, I can not enter anything for n in the second position, as if I already took something from the buffer.

Something like this:

Ingresar n (1):
aca_puedo_escribir
Ingresar a (1):
aca_puedo_escribir
Ingresar e (1):
10
Ingresar n (2): // ACA NO PUEDO INGRESAR NADA
Ingresar a (2):
aca_puedo
Ingresar e (2):
20

That is, n is "filled only", as if there was already something in the buffer, here goes the code:

struct unc{
    char n[30];
    char a[30];
    int e;
    };

int main(){
    struct unc l[5];
    int i;
    for (i=0;i<5;i++){
        printf("Ingresar n (%d):\n",i+1);
        gets(l[i].n);
        printf("Ingresar a (%d):\n",i+1);
        gets(l[i].a);
        printf("Ingresar e (%d):\n",i+1);
        scanf("%d",&l[i].e);
        }
    
asked by ssrlee 11.11.2016 в 23:18
source

2 answers

2

Your problem is that scanf() does not read the ENTER that you press when entering the integer. That's the way it is, and that's the way it should be.

You can try several things (the solution depends on each implementation of those particular functions):

  • scanf("%d\n",&l[i].e); (add a '\ n').
  • scanf("%d",&l[i].e); getc( stdin ); (we pick up that ENTER by hand).
  • answered by 12.11.2016 в 00:44
    0

    If you have trouble reading, just after the scanf, empty the input buffer. You can do this by including the following line: fflush(stdin) , since stdin is the standard input buffer.

        
    answered by 11.11.2016 в 23:29