Float Variables

So I am beginning in C++, and I am making a calculator. I made it work so you can plug in "5*5" or anything else and it will give the answer. But then I wanted to make it so you could put in "5*5" or "5*5+5", so I added another variable but it wont do the operation. So how do I make it so that it doesn't require the other variable?

#include<iostream>

using namespace std;
float a, b, c, result;
char calc;

int main()
{
cout << "Enter your calculation!" <<endl;
cin >> a >> calc >> b >> c;

if(calc == '+' )
{
result = a + b;
cout << a << " + " << b << " = " << result <<endl;

}
else if(calc == '-')
{
result = a - b;
cout << a << " - " << b << " = " << result <<endl;
}
else if(calc == '/')
{
result = a / b;
cout << a << " / " << b << " = " << result <<endl;
}
else if(calc == '*')
{
result = a * b;
cout << a << " * " << b << " = " << result <<endl;
}

else
{
cout<< "Incorrect operation please enter like this 5 + 5" <<endl;

}


return 0;
}
Hi, the main problem is simple: you read just one operator!

cin >> a >> calc >> b >> c;

To handle another operation, you would need another char variable where you would store the second operator... But now the problem is: how do you recognize when you are doing a 'simple' operation (like 5*5) or a 'complex' one (like 5*5+5)? You can't know it 'a priori', so probably the best (and more flexible) thing to do would be reading an entire line as a string and then parsing it to extract the relevant information, which are operands and operators.
You're adding a new character variable and a third integer which you don't include in any of your calculations.
So for example for "5 * 5 + 5".
a is 5
b is 5.
char is *.
It will go to the if(char == *) condition and multiply 5 * 5.
There's no data type assignment for the additional "+" character, nor is "c" included in any of the calculations.
Last edited on
Topic archived. No new replies allowed.