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;
}
thanks. solved here too
– Cauã Vilte
This sort of resolves by coincidence, this is not standard in a compiler that doesn’t work. http://c-faq.com/stdio/stdinflush.html
– Maniero
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.– Pablo Tondolo de Vargas
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.
– Maniero
Thanks, I’ll read it.
– Pablo Tondolo de Vargas