Basic Calculator

After running my code for a calculator program this is what happens. It doesn’t allow you to enter another number. I’m not sure what I am missing. Code is located below.

Enter a number: 3.2
Enter operator: /

Process returned -1073741819 (0xC0000005) execution time : 5.624 s
Press any key to continue.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{

double num1;
double num2;
char op;

printf(“Enter a number: “);
scanf(”%lf”, &num1);

printf(“Enter operator: “);
scanf(” %c”, op);

printf(“Enter a number: “);
scanf(”%lf”, &num2);

if(op == ‘+’){
printf("%f", num1 + num2);}
else if(op ==’-’){printf("%f", num1 - num2);}
else if(op ==’/’){printf("%f", num1 / num2);}
else if(op ==’*’){printf("%f", num1 * num2);}

return 0;

}

thank you

Hello @system4502423996, welcome to the forums! It appears that C wants you to use a pointer when getting an operator from the user:

As to the why, I’m not sure…

If I try that it throws an error

ISO C++ forbids comparison between pointer and integer [-fpermissive]|
||=== Build failed: 4 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

Strange; it works for me. Can you post your new code, please?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{

double num1;
double num2;
char* op;

printf(“Enter a number: “);
scanf(”%lf”, &num1);

printf(“Enter operator: “);
scanf(” %c”, op);

printf(“Enter a number: “);
scanf(”%lf”, &num2);

if(op == ‘+’){
printf("%f", num1 + num2);}
else if(op ==’-’){printf("%f", num1 - num2);}
else if(op ==’/’){printf("%f", num1 / num2);}
else if(op ==’*’){printf("%f", num1 * num2);}

return 0;
}

Hm; if you put an & before the op here, it seems to work:

Perhaps pointer was the wrong word to use before; I’m afraid I may be in a bit too deep in terms of my C knowledge…

2 Likes

No you can definitely use a pointer here, the important bit is passing an address for the newly “scanned” value to be stored in. So using the & (address-of) operator is quite common.

@system4502423996 you could equally use a named pointer here but then you’d need to dereference that same pointer when trying to compare it against character values later on. I would note though that your current compiler seems to mentioning issues related to C++ rules, if you’re writing C try to compile using C settings.

If you search around though you’ll probably find a fair amount of guidance warning against scanf for this (and suggesting things like fgets instead).

1 Like

I was following a YouTube tutorial and my code matched his but didn’t work. Now that you point it out I see it. Thanks

1 Like