Why doesnt this code work?
Im am a beginner and i wrote this so please tell me how to fix it

2 Answers
- ?Lv 76 years agoFavourite answer
first, answer needs to be char type
second, you need to compare it as follows
if(answer=='*') {...}
you need the single quotes for a single character literal...
and you have to get the value for your two numbers BEFORE you add them...
#include <iostream>
int main(void){
int a,b,sum;
char c;
cout << "welcome to my calculator\nplease enter * for multiply or + for add:"
cin >>c;
cout << " please enter the two numbers:"
cin << a << b;
if(c=='*')
cout << a*b;
else if(c=='+')
cout << a+b;
else
cout <<"huh?";
return 0;
}
- ChrisLv 76 years ago
Like the other answer says, you need to put the + and * in single quotes.
Then you need to deal with three cases, like this:
if (answer == "+") ...
else if (answer == '*') ...
else cout << "Invalid response"
Finally, you can't call "sum = a + b;" before actually reading a and b from the user. The computer is dumb, it won't wait until later, it will add a and b right when you tell it to.
If you had put your code on pastebin.com or some other side, I'd have fixed it. But I'm not going to type all that.