i am struggling with a string related problem in c++.
suppose i have a string s="6*6+4*8+6/6/6-632+81";
My main goal is to do the arithmetic operation from the string. So in the bellow code i am getting correct result when the integer value is a 1 digit integer.
string math[]="1+2"; Result:3;
but when the, string math[]="10+20" Then result is:2;
#include<iostream>
#include<string>
using namespace std;
int main()
{
int A,B,val;
char math[]="1+2";
//char math[]="10+20";
for (int i = 0 ; math[i]!=NULL; i++)
{
char ch =math[i];
if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
char ch2=math[i-1];
A=(ch2-'0');
char ch3=math[i+1];
B=(ch3-'0');
switch (ch) /* ch is an operator */
{
case '*':
val = A * B;
break;
case '/':
val = A / B;
break;
case '+':
val = A + B;
break;
case '-':
val = A - B;
break;
}
}
if ( math[i] == NULL)
{
break;
}
}
cout<<val<<endl;
}
so I realize the problem is choosing the value of A and B.Here I am not selecting the whole digit. so i want my A to be 10 and B 20.But my programm is selecting A=0 and B=2.So to get the whole digit .like A=10,i made these changes in my code[only for A.As a test].
if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
char total;
int k=i-1;
cout<<"k="<<k<<endl;
char p;
p=math[k];
for(;k>-1 && isdigit(p)==true;k--)
{
char c=math[k];
cout<<"c"<<c<<endl;
total=math[i-1];
total=total+c;
}
char ch2=total;
// char ch2=math[i-1];
cout<<"ch2:"<<total<<endl;
A=(ch2-'0');
cout<<"A="<<A<<endl;
BUT now for A i am getting garbage value.Now how can i solve this.More specifically get the value of A=10 and B=20 and get the correct result for this math expression.