stringstream - Cant get this to update the variables C++ -
i'm writing program calculator type in sum , give answer. part works fine. problem having taking answer of previous sum , doing calculation that.
like: 5 + 5 = 10 ans + 10 = 20
when run code below works fine, when doing normal calculations on , on again. when type eg. ans*2
uses previous values set operate
, numb
. if was: 5 + 5
, want use result , times eg 2 this: 10 + 5 = 15
here's 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 please me work. why operate
, numb
not update?
i suspect problem statement:
ss>>numa>>operate>>numb;
numa
, numb
of type double
. if input line example ans + 10
, statement try extract numa
double start of input, fail, without consuming parts of input string. consequence, extracting remaining values (operate
, numb
) not give expected values, because whole input string still left parsed when gets extracting values.
one approach check ans
case first, after reading input line. can make statement above conditional, parsing values differently ans
case.
another solution first extract numa
, numb
values string variables, , convert them doubles after checked ans
special case.
Comments
Post a Comment