I'm trying to build a simple calculator using C and the switch case. If I try to use characters instead of integers, the program doesn't work: it reads what I type into the input buffer and it stores it into the variables, but it doesn't recognize any case. What am I doing wrong? I'm sorry if this question is a duplicate, I tried to search for a solution, but my code is looking fine to me, so I don't understand what is wrong.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char s[80], op[80];
int num1, num2, res;
printf("Please type your operation:\n");
fgets (s, sizeof(s), stdin);
num1 = atoi(s);
fgets (op, sizeof(op), stdin);
fgets (s, sizeof(s), stdin);
num2 = atoi(s);
switch (op[80]) {
case ' ' :
res = num1 num2;
printf("%i\n", res);
break;
case '*' :
res = num1 * num2;
printf("%i\n", res);
break;
default:
return 1;
}
return 0;
}
CodePudding user response:
You're reading into op
which is a character array of length 80, but then switch
-ing on op[80]
which is (just) beyond the length of op
. Try changing that to op[0]
to mean the first character of op
.