In C++ Enhance the class you created (let\'s call it mathExp class) to include e
ID: 3762174 • Letter: I
Question
In C++
Enhance the class you created (let's call it mathExp class) to include evalfunctions. The operators shall include +,-,*,/,(,) as minimum.
Write a main.cpp that creates a few test example mathExp objects that demonstrates the working of your mathExp class. Sample is below. Add more expressions if you implement other operators, e.g. exp.
Sample:
#include <iostream>
using namespace std;
#include "mathExp.h"
int main()
{
mathExp ex1("3+1*2-(2*1+1)/3");
mathExp ex2 ("3+(++1)*2-(2*1.5+1)/3");
cout << "Name : id xxxxxx" << endl;
cout << ex1 << endl << "convert to: " << ex1.showPostfix() << endl;
cout << "eval to: " << ex1.eval() << endl;
cout << ex2 << endl << "convert to: " << ex2.showPostfix() << endl;
cout << "eval to: " << ex2.eval() << endl;
// add other things you like to show...
}
Explanation / Answer
#include <iostream.h>
#include <string.h>
#include <ctype.h>
const int MAX = 50 ;
class mathExp
{
private :
char target[MAX], stack[MAX] ;
char *s, *t ;
int top ;
public :
infix(char *str ) ;
void push ( char c ) ;
char pop( ) ;
void convertToPostfix( ) ;
int precedence ( char c ) ;
void showPostfix( ) ;
} ;
mathExp :: mathExp(char *str )
{
top = -1 ;
strcpy ( target, "" ) ;
strcpy ( stack, "" ) ;
t = target ;
s = str ;
}
void mathExp :: push ( char c )
{
if ( top == MAX )
cout << " Stack is full " ;
else
{
top++ ;
stack[top] = c ;
}
}
char mathExp :: pop( )
{
if ( top == -1 )
{
cout << " Stack is empty " ;
return -1 ;
}
else
{
char item = stack[top] ;
top-- ;
return item ;
}
}
void mathExp :: convertToPostfix( )
{
while ( *s )
{
if ( *s == ' ' || *s == ' ' )
{
s++ ;
continue ;
}
if ( isdigit ( *s ) || isalpha ( *s ) )
{
while ( isdigit ( *s ) || isalpha ( *s ) )
{
*t = *s ;
s++ ;
t++ ;
}
}
if ( *s == '(' )
{
push ( *s ) ;
s++ ;
}
char opr ;
if ( *s == '*' || *s == '+' || *s == '/' || *s == '%' || *s == '-' || *s == '$' )
{
if ( top != -1 )
{
opr = pop( ) ;
while ( precedence ( opr ) >= precedence ( *s ) )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
push ( opr ) ;
push ( *s ) ;
}
else
push ( *s ) ;
s++ ;
}
if ( *s == ')' )
{
opr = pop( ) ;
while ( ( opr ) != '(' )
{
*t = opr ;
t++ ;
opr = pop( ) ;
}
s++ ;
}
}
while ( top != -1 )
{
char opr = pop( ) ;
*t = opr ;
t++ ;
}
*t = '' ;
}
int mathExp :: precedence ( char c )
{
if ( c == '$' )
return 3 ;
if ( c == '*' || c == '/' || c == '%' )
return 2 ;
else
{
if ( c == '+' || c == '-' )
return 1 ;
else
return 0 ;
}
}
void mathExp :: showPostfix( )
{
cout << target ;
}
void main( )
{
mathExp ex1("3+1*2-(2*1+1)/3");
mathExp ex2 ("3+(++1)*2-(2*1.5+1)/3");
ex1.convertToPostfix();
ex2.convertToPostfix();
cout << ex1 << endl << "convert to: " << ex1.showPostfix() << endl;
//cout << "eval to: " << ex1.eval() << endl;
cout << ex2 << endl << "convert to: " << ex2.showPostfix() << endl;
//cout << "eval to: " << ex2.eval() << endl;
}
Note: Eval method not implemented.