Home > OS >  "lvalue required as left operand of assignment" for all of my if/else statements. What hav
"lvalue required as left operand of assignment" for all of my if/else statements. What hav

Time:02-10

I'm making a basic calculator that uses if/else statements to select a sign to use in the equation. All of the else/if statements are reporting an error:

error: lvalue required as left operand of assignment

#include <iostream>
using namespace std;

int main()
{
    //declare variables

    int num1;
    int num2;
    int sol;
    bool sign;

    //prompt for num1
    cout << "Greetings! Please enter a number." << endl;
    cin >> num1;

    //prompt for num2
    cout << "Great! Now, please enter the second number." << endl;
    cin >> num2;

    //prompt for sign
    cout << "Almost there! Now, please enter the sign you wish to use in the equation." << endl;
    cin >> sign;

    //arguments
    if (sign == ' ')
    {
        num1   num2 = sol;
    }
    else if (sign == '-')
    {
        num1 - num2 = sol;
    }
    else if (sign == '*')
    {
        num1 * num2 = sol;
    }
    else if (sign == '/')
    {
        num1 / num2 = sol;
    }
    else
    {
        cout << "Sorry, that is not a valid symbol." << endl;
        return 0;
    }

    //print results
    cout << "The solution is: " << sol << endl;
    return 0;
}

CodePudding user response:

You have your assignments reversed. = is not a commutative operator.

They should all be of the form

sol = num1 op num2

What you are trying to do is assign the (uninitialised) value of sol to the unnamed temporary that results from the calculation. Happily this is a hard error with fundamental types.

  • Related