So I made a simple calculator that takes two numbers and a basic operation (+,-,*,/) and then prints out the result, and also an error message is printed when anything other than those four operators is entered. But I have these questions that I couldn't quite find the answers for:
1-How do I make a while loop that makes the program print an Error message and asks the user to enter the two numbers and the operation again when anything other than a number is entered into either %d's in the scanf?
2- Why does the program print out the error message infinitely when anything other than numbers is entered into either %d's in the scanf or when I try to enter each variable seperately (For example: 10 Enter / Enter 5 Enter, the program starts printing out the error message infinitely after I press enter after the "/").
Here is my code:
#include <math.h>
#include <stdio.h>
int main()
{
double n1=0.0,n2=0.0,result=0.0;
char operation=' ';
scanf("%lf%c%lf", &n1,&operation,&n2);
while(operation!='+' && operation!='-' && operation!='*' && operation!='/')
{
printf("Error! Invalid Operator.\n");
scanf("%lf%c%lf", &n1,&operation,&n2);
}
if(operation=='+')
{
result=n1+n2;
printf("%f",result);
}
else if(operation=='-')
{
result=n1-n2;
printf("%f",result);
}
else if(operation=='*')
{
result=n1*n2;
printf("%f",result);
}
if(operation=='/')
{
result=n1/n2;
printf("%f",result);
}
return 0;
}