Program does not execute without reading the contents of the variable

1

I'm creating a simple program for a college job, which reads 2 numbers, an arithmetic operator and returns the result of that operation. But it happens that after printing on the screen "enter the operator", the program does not expect me to enter the character, but ends the program soon. What is wrong? follow the code.

#include <stdio.h>
int main() {
    float n1,n2;
    char op;

    printf("Digite o primeiro operando: \n");
    scanf("%f", &n1);

    printf("Digite o segundo operando: \n");
    scanf("%f", &n2);

    printf("Digite um dos operadores aritmeticos (+,-,* ou /): \n");
    scanf("%c", &op);

    if (op == '+')
      printf("%f, %c",n1,op,n2,"=",n1+n2);
    else if (op == '-')
       printf("%f, %c",n1,op,n2,"=",n1-n2);
    else if (op == '*')
        printf("%f, %c",n1,op,n2,"=",n1*n2);
    else if (op == '/') {
        while (n2=0) {
            printf("Digite o divisor não nulo: \n");
            scanf("%f", &n2);
        }
        printf("%f, %c",n1,op,n2,"=",n1/n2);
    }
    else
        printf("Operador invalido! \n");

    return 0;             
}
    
asked by anonymous 25.02.2017 / 17:09

1 answer

0

Cauã, what I did to solve your problem, was to put a blank before %c

printf("Digite um dos operadores aritmeticos (+,-,* ou /):\n");
scanf(" %c", &op);

You do not need to use white space, so you can use fflush

fflush(stdin);      
printf("Digite um dos operadores aritmeticos (+,-,* ou /):\n"); 
scanf("%c", &op);
    
25.02.2017 / 17:34