0

I have this sheet of code:

listCh remplir(){
    char rep;
    listCh l,aux,p;
    printf("1-veuillez entrer un element?(n pour quitter)\n");
    scanf("%c",&rep);
    if(rep=='n')
        l=NULL;
    else{
        l=malloc(sizeof(listCh));
        printf("2-Donnez la valeur d element!\n");
        scanf("%d",&l->valeur);
        p=l;
    }
    while(rep!='n'){
        printf("voulez-vous ajouter un nouveau element de la list? (n pour quitter)\n");
        scanf("%c",&rep);
        if(rep!='n'){
            aux=malloc(sizeof(listCh));
            printf("Donnez la valeur d element!\n");
            scanf("%d",aux->valeur);
            p->suiv=aux;
            p=aux;
        }
        else{
            p->suiv=NULL;
        }

    }
    return l;
}

There is no error while executing ! But, the problem is that my program escapes the first "scanf" function in the "while" loop.

I didn't find an explanation for this.

I need some help please.

Many thanks :)

akram1rekik
  • 153
  • 1
  • 1
  • 7
  • 2
    Possible duplicate of [Reading newline from previous input when reading from keyboard with scanf()](http://stackoverflow.com/questions/29905009/reading-newline-from-previous-input-when-reading-from-keyboard-with-scanf) – MikeCAT Dec 02 '15 at 00:04
  • Really no error? `listCh l; l=malloc(sizeof(listCh));` seems strange. – MikeCAT Dec 02 '15 at 00:05
  • 1) `scanf("%d",&(aux->valeur));` (add &) Check your compiler setting. A good compiler would warn about this. 2) `scanf("%c",&rep);` --> `scanf(" %c",&rep);` (add space) – chux - Reinstate Monica Dec 02 '15 at 00:11

2 Answers2

3

Always remember to put a space before %c when scanf() a character variable. A bit unusual, but that's how to skip all the buffered spaces in the input stream before you can get the real character.

scanf("%c",&rep); should be scanf(" %c",&rep);

artm
  • 17,291
  • 6
  • 38
  • 54
1

It is probably reading your enter from your first scanf.
Try putting a getchar() before your scanf on the loop

Jorgel
  • 920
  • 3
  • 14
  • 28