I translated to C++ and enhanced a Pascal arithmetic expression evaluator program found in “Applied Data Structures Using Pascal” by Guy J. Hale and Richard E. Easton. The original code used single digit numbers. As an exercise I enhanced the application to utilize multiple digit numbers. Below is my test file and output from my program. I used the C++ standard library stack data structure.
20 + 3 * 4 + 50 * 4 * 2 + 6 * 2 - 8 / 2 + 2 ^ 5

#pragma once
#include <fstream>
#include <stack>
using namespace std;
class Expression
{
public:
char ch, sign, termOp;
int number;
stack<int> stk;
void GetChar(fstream& inps);
void GetExpression(fstream& inps);
void GetFactor(fstream& inps);
void GetTerm(fstream& inps);
};
#include "pch.h"
#include "Expression.h"
#include <math.h>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
void Expression::GetChar(
fstream& inps)
{
while (!inps.eof())
{
ch = (char)inps.get();
if (inps.eof())
exit(1);
if (ch >= '0' && ch <= '9')
return;
if (ch == '^' || ch == '*' || ch == '/')
return;
if (ch == '+' || ch == '-')
return;
if (ch == ' ' || ch == '\t' || ch == '\n')
continue;
if (ch == ';')
return;
}
}
void Expression::GetExpression(fstream& inps)
{
int num, num1, num2;
if (ch == '+' || ch == '-')
{
sign = ch;
GetChar(inps);
GetTerm(inps);
if (sign == '-')
{
num = stk.top();
stk.pop();
num = -num;
stk.push(num);
}
}
GetTerm(inps);
while (ch == '+' || ch == '-')
{
termOp = ch;
GetChar(inps);
GetTerm(inps);
num2 = stk.top();
stk.pop();
num1 = stk.top();
stk.pop();
if (termOp == '+')
num = num1 + num2;
else
num = num1 - num2;
stk.push(num);
}
}
void Expression::GetFactor(fstream& inps)
{
if (ch >= '0' && ch <= '9')
{
string str;
while (ch >= '0' && ch <= '9' && !inps.eof())
{
str += ch;
ch = (char)inps.get();
if (ch == ' ' || ch == '\t' || ch == '\n')
break;
else if (ch == '^' || ch == '+' || ch == '-' ||
ch == '*' || ch == '/')
break;
}
if (inps.eof())
exit(-1);
while (ch == ' ' || ch == '\t' || ch == '\n')
ch = (char)inps.get();
number = atoi(str.c_str());
stk.push(number);
return;
}
else
{
GetChar(inps);
GetExpression(inps);
GetChar(inps);
}
}
void Expression::GetTerm(fstream& inps)
{
char factOp;
int num, num1, num2;
GetFactor(inps);
while (ch == '*' || ch == '/' || ch == '^')
{
factOp = ch;
GetChar(inps);
GetFactor(inps);
num2 = stk.top();
stk.pop();
num1 = stk.top();
stk.pop();
if (factOp == '*')
num = num1 * num2;
else if (factOp == '/')
num = num1 / num2;
else if (factOp == '^')
num = (int)pow(num1, num2);
stk.push(num);
}
}
#include "pch.h"
#include "Expression.h"
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
bool validExp;
int expVal;
fstream inps;
Expression ex;
inps.open("TestExp.txt", fstream::in);
if (!inps.eof())
{
validExp = true;
ex.GetChar(inps);
ex.GetExpression(inps);
expVal = ex.stk.top();
ex.stk.pop();
cout << "Value = " << expVal << endl;
}
else
{
validExp = false;
expVal = 0;
}
return 0;
}