In an attempt to help learn C I’ve been trying to write a simple calculator, but I’m stuck on the issue of scanf not assigning the inputted value to a variable.
I’ve seen people recommend fgets over scanf but that brought more issues so I decided to stick with scanf for now.
the reason I have all the getchar(); and ” %dn” included in there is because the program would skip directly past those inputs otherwise.
Thank you.
#include <stdio.h>
#include <string.h>
int main() {
int numberOne;
int numberTwo;
int result;
char operation[8];
printf("Enter your first number: n");
scanf(" d%n", &numberOne);
getchar();
printf("Enter your second number: n");
scanf(" d%n", &numberTwo);
getchar();
printf("Enter the operation to perform on these numbers. n");
printf("Add, Subtract, Multiply, Divide. n");
scanf(" s%n", &operation);
printf("operation=%sn", operation);
printf("numberOne=%dn", numberOne);
printf("numberTwo=%dn", numberTwo);
if (strcmp(operation, "Add") == 0) {
result = numberOne + numberTwo;
printf("d%", result);
return result;
}
if (strcmp(operation, "Subtract") == 0) {
result = numberOne - numberTwo;
printf("d%", result);
return result;
}
if (strcmp(operation, "Multiply") == 0) {
result = numberOne * numberTwo;
printf("d%", result);
return result;
}
if (strcmp(operation, "Divide") == 0) {
result = (float) numberOne / numberTwo;
printf("f%", result);
return result;
}
}
ringojuice is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6