I am a bare bones beginner, so there definitely could be something obvious I'm missing, but for some reason this code keeps outputting the first variable instead of the sum, subtraction, etc.
#include <stdio.h>
int main(){
int numone=0, numtwo=0;
char sign;
printf("Please enter the first number: ");
scanf("%d", &numone);
printf("Please enter the second number: ");
scanf("%d", &numtwo);
printf("Please enter the operation: ");
scanf("%s", &sign);
switch (sign) {
case '+':
printf("The result is: %d", numone + numtwo);
break;
case '-':
printf("The result is: %d", numone - numtwo);
break;
case '*':
printf("The result is: %d", numone * numtwo);
break;
case '/':
printf("The result is: %d", numone / numtwo);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
%s
in scanf()
expects a multi-byte buffer for input chars and null terminator, but &sign
points to a single byte. You definitely wanted to read a single char and should have used %c
. Try this
scanf(" %c", &sign)
Note the space prior %c
, it lets us skip whitespaces before a significant character.