Code does not execute a second " var = getchar(); " if an if is true

Asked

Viewed 21 times

0

Why the code below does not allow me to fill in the 'ext' variable if the established condition has been accepted?

#include <stdio.h>
#include <stdlib.h>
void main(){
    char ext;
    char dif;

    dif = getchar();

    if(dif=='p'||dif=='P'){
        printf("\nVoce digitou %c",dif);
        ext = getchar();
        printf("\nVoce digitou %c",ext);
        printf("\nDONE");
        exit(0);
    }
    else{
        printf("\nShame on you buddy");
        exit(0);
    }
}

output :

P

Voce digitou P
Voce digitou

DONE
--------------------------------
  • 1

    See, for example, https://answall.com/questions/43691/limpeza-do-buffer-ap%C3%b3s-getchar

  • This question is duplicated. As pointed out by the user Runo the problem lies in the cleaning of the buffer. An alternative is to use scanf with a space before %. For example, on line 11 we would have : " scanf("-%c",&dif); ", where -- represents a space. This clears the buffer and allows filling other variables with other entries.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.