# Thread: Need help with simple calculator

1. ## Need help with simple calculator

Hello. I started learning C today, and found myself trying to write a simple calculator program. However, after attempting the operation "5+4", I get the answer 32704. Using other operations produces similar results. I appreciate any help you can give me.

EDIT:
Here's the code in a nice tag:
Code:
```#include <stdio.h>
#include <stdlib.h>
int main()
{
int q;
int q2;
int q3;
char w[16];
char o[16];
puts("Enter the first number:");
scanf("&#37;s",w);
q=atoi(w);
puts("Enter the second number:");
scanf("%s",w);
q2=atoi(w);
puts("Enter the operator:");
scanf("%s",o);
if (o == "+")
{
q3=q+q2;
}
if (o == "-")
{
q3=q-q2;
}
if (o == "/")
{
q3=q/q2;
}
if (o == "*")
{
q3=q*q2;
}
printf("%d %s %d = %d\n",q,o,q2,q3);
return(0);
}```

2. > if (o == "+")

Doesn't do what you think it does, in this case the address of o will be compared with the address of "+" (wherever that may be). Use strcmp() or since they're single characters, if(o[0] == '+') or something.

Other than that, you have 3 flaws.
1) is the potential buffer overflow, if they enter > 15 characters for the "first number".
2) and you can just use scanf() to read the numbers in.
3) q3 has no defined value if none of the operators are "caught" (perhaps have a if/else if/else structure? Or switch as below)

Your weird answer comes from the fact none of those "if's" are true, and q3 is uninitialized (ie full of "random").

Here is a "fix":
Code:
```int a = 0,
b = 0,
ans = 0;
char op;        /* operator */

if(scanf("&#37;d%c%d", &a, &op, &b) != 3)
{
// some error
}

switch(op)
{
case '+':
ans = a + b;
break;

default:
// unknown op
}

// print answer if you want...```
Which would allow you to enter, "6+5" all on one line (don't have to use that idea however).

3. I understand now. Thank you very much.