This is a simple calculator program I made
#include <stdio.h>
int main (){
int x,y,h;
char z;
x=0;
y=0;
h=0;
printf ("x: ");
scanf ("%d", &x);
printf ("y: ");
scanf ("%d", &y);
//while ((z = getchar()) != '\n' && z != EOF);
printf ("z: ");
scanf("%c",&z);
if (z == '+') {
h=x+y; printf ("%d", h);
getch();
}
else if (z == '-') {
h=x-y; printf ("%d", h);
getch();
}
else if (z == '*') {
h=x*y; printf ("%d", h);
getch();
}
else if (z == '/') {
h=x/y; printf ("%d", h);
getch();
}
return 0;
}
The strange part is, after z: printed, then the program suddenly quits.
I don't understand why. It's supposed to ask input for z.
But when I add this line before printf("z: ") :
while ((z = getchar()) != '\n' && z != EOF);
Then the program runs correctly. Any idea why?