0

I'm trying to write calculator code in C for loop. The problem it runs good at first iteration only. the next iterations it ignores scanf command so it gives wrong output.

#include <stdio.h>
#include <stdlib.h>

int main(){
int i ;
char operator_;
double x, y;
for (i = 1; i <= 3; ++i)
{
printf("Enter an operator (+, -, *,/): ");
scanf("%c",&operator_);
printf("\nEnter the first number: ");
scanf("%lf",&x);
printf("Enter the second number: ");
scanf("%lf",&y);
switch (operator_) {
case '+':
printf("The sum equals to %lf + %lf = %lf\n\n\n", x, y, x + y);
break;
case '-':
printf("The difference equals to %lf - %lf = %lf\n\n\n", x, y, x - y);
break;
case '*':
printf("The product equals to %lf * %lf = %lf\n\n\n", x, y, x * y);
break;
case '/':
printf("The quotient equals to %lf / %lf = %lf\n\n\n", x, y, x / y);
break;
default:
printf("Error! operator is not correct\n\n\n");
}
}
printf("\nyour trial period has ended\n\n\n");
return 0;

}
Ahmad Kandil
  • 35
  • 1
  • 7
  • 1
    Does this answer your question? [scanf Getting Skipped](https://stackoverflow.com/questions/14484431/scanf-getting-skipped) – kaylum Apr 29 '21 at 03:18
  • 2
    Try: `scanf("%c",&operator_);` -> `scanf(" %c",&operator_);`. That is, add space before `%c` – kaylum Apr 29 '21 at 03:19
  • OT: for ease of readability and understanding (the compiler doesn't care) Please consistently indent the code,. Indent after every opening brace '{'. Unindent before every closing brace '}'. Suggest each each indent level be 4 spaces, – user3629249 Apr 29 '21 at 15:56

0 Answers0