I am working on a home work assignment which is:
"Write a program that will allow the user to enter an infix expression terminated by '=' your program will convert to Postfix notation"
enter 3+7-6/2*8+7=
prints 3 7 + 6 2 / 8 * - 7 +
I have written the code below to complete this useing single digits, but I want to allow the user to put in any number and have it do the same
ie 37+47/12 prints 37 47 + 12/
This is not part of the assignment, but I have the next two week to fiddle with it.
Any suggestion? I am lost at the moment.
Thanx in advance!
Lanier
char InOp1='#'; //Holds values to be compared in switch case.
char InOp2='#'; //Holds value for comparison to properly push onto stack.
LinkedStack Cal; //stack used to hold info in postfix format
void In2Post()
{
cin>>InOp1;
while(InOp1!='=')
{
//while loop to push digits on to stack
while(InOp1!='+'&&InOp1!='-'&&InOp1!='*'&&InOp1!='/'&&InOp1!='('&&InOp1!=')'&&InOp1!='?')
{
Cal.Push(InOp1);
cin>>InOp1;
}
switch(InOp1) //switch case used to properly format stack
{
case '+': cin>>InOp2;
if(InOp2=='+'||InOp2=='-'||InOp2=='*'||InOp2=='/'||InOp2=='('||InOp2==')')
{
cout<<"Incorrect input "<<InOp2<<" cannot follow + sign."<<endl<<"Must be digit.";
InOp1='?';
break;
}
else
{
Cal.Push(InOp2);
Cal.Push(InOp1);
cin>>InOp1;
break;
}
case '-': cin>>InOp2;
if(InOp2=='+'||InOp2=='-'||InOp2=='*'||InOp2=='/'||InOp2=='('||InOp2==')')
{
cout<<"Incorrect input "<<InOp2<<" cannot follow - sign."<<endl<<"Must be digit.";
InOp1='?';
break;
}
else
{
Cal.Push(InOp2);
Cal.Push(InOp1);
cin>>InOp1;
break;
}
case '/': cin>>InOp2;
if(InOp2=='+'||InOp2=='-'||InOp2=='*'||InOp2=='/'||InOp2=='('||InOp2==')')
{
cout<<"Incorrect input "<<InOp2<<" cannot follow / sign."<<endl<<"Must be digit.";
InOp1='?';
break;
}
else
{
Check=Cal.Top();
if(Check=='+'||Check=='-')
{
Cal.Pop();
Cal.Push(InOp2);
Cal.Push(InOp1);
Cal.Push(Check);
Check='#';
cin>>InOp1;
break;
}
else
{
Cal.Push(InOp2);
Cal.Push(InOp1);
Check='#';
cin>>InOp1;
}
}
case '*': cin>>InOp2;
if(InOp2=='+'||InOp2=='-'||InOp2=='*'||InOp2=='/'||InOp2=='('||InOp2==')')
{
cout<<"Incorrect input "<<InOp2<<" cannot follow * sign."<<endl<<"Must be digit.";
InOp1='?';
break;
}
else
{
Check=Cal.Top();
if(Check=='+'||Check=='-')
{
Cal.Pop();
Cal.Push(InOp2);
Cal.Push(InOp1);
Cal.Push(Check);
Check='#';
cin>>InOp1;
break;
}
else
{
Cal.Push(InOp2);
Cal.Push(InOp1);
Check='#';
cin>>InOp1;
}
}
case '(':case ')': cin>>InOp1;
break;
default: cout<<endl<<"Input data contains error can not continue."<<endl<<endl;
system("pause");
return 0;
}
}