Program does not run without reading the contents of the variable

Asked

Viewed 35 times

1

I am creating a simple program for a college job, which reads 2 numbers, an arithmetic operator and returns the result of that operation. But it turns out that after printing on the screen "type the operator", the program does not wait for me to enter the character, but finishes the program. What is the error? follows 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;             
}

1 answer

0


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

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

For you do not need to use the blank space, you can use the fflush

fflush(stdin);      
printf("Digite um dos operadores aritmeticos (+,-,* ou /):\n"); 
scanf("%c", &op);
  • thanks. solved here too

  • This sort of resolves by coincidence, this is not standard in a compiler that doesn’t work. http://c-faq.com/stdio/stdinflush.html

  • Yes, I read a little over and have found articles not recommending the use of scanf. But for a solution until it worked out what I proposed, @bigown you could answer with the best solution for this case.

  • You already have an answer on this at http://answall.com/q/42981/101. I already made an example with the solution: http://answall.com/a/107226/101. You have more information at http://answall.com/q/87973/101. And also: http://answall.com/q/9427/101. If you search Sopt here you have several other answers about this.

  • Thanks, I’ll read it.

Browser other questions tagged

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