I'm writing a program that is a calculator where you would type in the sum and it would give you the answer. That part works fine. The problem I am having is taking the answer of the previous sum and doing a calculation with that.
Like: 5 + 5 = 10
ans + 10 = 20
When I run the code below it works fine, when doing normal calculations over and over again. However when I type eg. ans*2
it uses the previous values set to operate
and numB
. So if it was: 5 + 5
and I want to use that result and times it by eg 2 it would do this:
10 + 5 = 15
Here's my code:
#include <iostream>
#include <cmath>
#include <iomanip>
#include <sstream>
#include "bell.h"
using namespace std;
int main()
{
stringstream ss;
double numA;
char operate;
double numB;
double ans=0;
string temp;
cout<<"input: ";
getline(cin, temp);
ss.str(temp);
ss>>numA>>operate>>numB;
cout<<setprecision(9);
while(temp[0] != 'q' && temp[0] != 'Q')
{
if(temp[0]=='a' && temp[1]=='n' && temp[2]=='s')
{
numA=ans;
}
switch(operate)
{
case '+':
{
ans=numA+numB;
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
case '-':
{
ans=numA-numB;
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
case '*':
{
ans=numA*numB;
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
case '/':
{
ans=numA/numB;
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
case '^':
{
ans=pow(numA, numB);
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
case 'z':
{
ans=bell(numA, numB);
cout<<numA<<" "<<operate<<" "<<numB <<" = "<< ans<<endl;
break;
}
default:
{
cout<<"Invalid input. Please try again!"<<endl;
}
}
ss.clear();
ss.str(" ");
cout<<"Input: ";
getline(cin, temp);
ss.str(temp);
ss>>numA>>operate>>numB;
}
cout<<"Goodbye"<<endl;
return 0;
}
Could someone please help me get this to work. Why does operate
and numB
not update?