Expected 'a' before 'a'

I am brand new to C++ and attempting to start with a simple program that adds or multiplies numbers based on the user's input. I seem to be getting the same error (see title). I didn't see anything previously posted.

int num1, num2, answer;
int sum;
sum = 0;
cout << "Please enter an integer: ";
cin>> num1;

cout << "Please enter another integer: ";
cin >> num2;
sum = sum + num1 + num2;

cout << "Would you like to compute the sum (s) or product (p) of the numbers? "
cin>> answer;

if (answer = s){
cout << "The sum is " <<sum << endl;
} else {
cout << "The product is " <<num1*num2 << endl;


Sorry if it's confusing. I had issues inserting the code.
copy and paste a complete program file that includes the main declaration, headers included, highlight it, and click the <> button to the right of the edit box, and under the word Format:
You declare answer as an int, but it should be a char. when you compare answer to s, you have a couple problems. s needs to be in single quotes like this: 's'. Also, saying answer = 's' will set answer to s, rather than comparing answer and s. You need to do answer == 's' instead. The double equals is comparison, while the single is assignment.
closed account (3qX21hU5)
sum = sum + num1 + num2;

This should be sum = num1 + num2;

There is no need to have the sum in the statement.

also you should change the else to else if (answer == 'p'. Otherwise if the user entered anything but 's' it would always go to the else statement. This way it only prints the product if the user enters a 'p'.

Otherwise I think freddy covered most of it.
Last edited on
Good catch on improper use of assignment operator. I didn't notice that at first. Another strategy that avoids the unexpected run-time behavior is to always put a constant on the left of the comparison like so:

1
2
3
4
if ( 's' == answer)  // compiles and runs as you'd expect
if ( 's' = answer) // doesn't compile
if (answer = 's') // compiles, but results in unexpected behavior most of the time.  
if (answer = getAnswer()) // assign value and evaluate result of return so this is one case where assignment within conditional can work as expected 
Topic archived. No new replies allowed.