How to read character data within an if conditional?

1

My problem is that according to a whole number, for example 1, the conditional would be fulfilled and therefore, I would have to read the data I am requesting, of a character type. When performing this action, at the time of entering the number 1, the program ends without reading my character data. This is an example, it is just a test and it is short, I would appreciate it if you could help me with this doubt, thanks: The declared variables are random words, the important thing is the code.

#include<stdio.h>

int main(){

    int torta;
    char dia;

    scanf("%d",&torta);

        if(torta == 1){
            printf("Ingresa una letra");
            scanf("%c",&dia);
        }
    return 0;
}
    
asked by Juan Carlos 13.06.2018 в 08:39
source

1 answer

2

The problem is in the input buffer left on the keyboard. When you make scanf("%d",&torta); you save a whole number in the variable cake. If you put a 1 it enters the condition. In it, you ask to pick up a character scanf("%c",&dia); but it "jumps" because it keeps the "enter" of scanf("%d",&torta);

To solve easily, you just have to put a blank space in front of " %c" .

It would stay like this:

#include<stdio.h>

int main(){

    int torta;
    char dia;

    scanf("%d",&torta);

        if(torta == 1){
            printf("Ingresa una letra");
            scanf(" %c",&dia); //<-- Insertar espacio en blanco
        }
    return 0;
}
    
answered by 13.06.2018 в 08:53