Calling for help~~~

Hello, everyone. I wrote my code to compute the value of an equation written with characters. That is to say, I key in "7*2+(6+3)*4#", I should get the result of 50. But there is something wrong with my code. Can anybody help me?
Thank you so much~~~
The following is my code:

#include<iostream>
#include<stack>
#include<deque>

using namespace std;
//Define the priority of calculation.//
int preference(char x)
{
switch(x)
{
case '+':
case '-':return 1;
case '*':
case '/':return 2;
default:return 0;
}
}
//Read chars into an array.//
void readin(char Origin[])
{
char ch;
int ix=0;
while((ch=getchar())!='\n'){
Origin[ix]=ch;
ix++;
}
}
//Push chars from the array to the stack.//
void inverse(char *Origin,stack<char> Out)
{
char ch;
int ix=0;
while((ch=Origin[ix])!='\0'){
Out.push(ch);
ix++;
}
}
void unit_insert(char x,stack<char> A,stack<char> B)
{
switch(x)
{
case '+':
case '-':
case '*':
case '/':
{
if(preference(x)>=preference(A.top())||A.empty()==true){
A.push(x);
return;
}
else {
while(preference(x)<preference(A.top())){
B.push(A.top());
A.pop();
}
A.push(x);
return;
}
}
case '(':
A.push(x);
case ')':
while(A.top()!='('){
B.push(A.top());
A.pop();
}
A.pop();
case '#':
while(A.top()!=' '){
B.push(A.top());
A.pop();
}
default:B.push(x);
}
}
void AinvtoB(stack<char> A,stack<char> B)
{
while(A.empty()==false){
B.push(A.top());
A.pop();
}
}
int unit_compute(char x,char y,char z){
switch(z)
{
case '+': return (int(x)+int(y));
case '-': return (int(x)-int(y));
case '*': return (int(x)*int(y));
case '/': return (int(x)/int(y));
}
}
void unit_deal(stack<char> A)
{
stack<char> B;
while(A.top()!='+'&&A.top()!='-'&&A.top()!='*'&&A.top()!='/'){
B.push(A.top());
A.pop();
}
if(A.top()!='+'||A.top()!='-'||A.top()!='*'||A.top()!='/'){
char z=A.top();
A.pop();
char x=B.top();
B.pop();
char y=B.top();
B.pop();
A.push(unit_compute(x,y,z));
while(B.top()!=' '){
A.push(B.top());
B.pop();
}
}
}
void total_deal(stack<char> A){
while (A.size()!=1){
unit_deal(A);
}
cout<<"The answer is: "<<A.top()<<".\n";
}
int main()
{
char Origin[100];
readin(Origin);
stack<char> A;
stack<char> B;
inverse(Origin,B);
AinvtoB(B,A);
stack<char> C;
stack<char> D;
while(A.empty()==false){
unit_insert(A.top(),C,D);
A.pop();
}
stack<char> E;
AinvtoB(D,E);
total_deal(E);
return 0;
}














Last edited on
Are you doing math without the math.h include?
<math.h> is redundant with C++ you need <cmath>
Topic archived. No new replies allowed.