Here's an actual working math parser. It only works with addition and subtraction though. You've got me interested now, so I'm gonna write a (much more useful) class for this problem.
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
string sFormula = "";
string sBuffer;
char szFormula[255];
bool numStream(false);
int iVal[2] = {0};
int iReturnVal(0);
int iCount(0);
char cLastOperator(0);
cout << "Enter formula: ";
cin.getline(szFormula, 54);
for (unsigned int i(0); i < strlen(szFormula); ++i)
{
if (isdigit(szFormula[i]))
{
numStream = true;
sBuffer += szFormula[i];
}
if (numStream && (!isdigit(szFormula[i]) || i == strlen(szFormula) - 1))
{
numStream = false;
iVal[iCount++] = atoi(sBuffer.c_str());
if (cLastOperator == '+')
{
iReturnVal += iVal[0] + iVal[1];
iVal[0] = 0;
iVal[1] = 0;
iCount = 0;
cLastOperator = 0;
}
else if (cLastOperator == '-')
{
iReturnVal -= iVal[0] + iVal[1];
iVal[0] = 0;
iVal[1] = 0;
iCount = 0;
cLastOperator = 0;
}
sBuffer = "";
}
if (!numStream && (szFormula[i] == '+' || szFormula[i] == '-' || szFormula[i] == '*'))
{
cLastOperator = szFormula[i];
}
}
cout << szFormula << " = " << iReturnVal << endl;
cin.get();
return 0;
}
It works like this:
Input a stream of numbers and operands (- or +), all seperated by a space. Ie 2 + 6 + 8 - 11
And it will output the result. It won't throw any exceptions, so if you see eratic results you probably entered the equation wrong.
Last edited by skatamatic; Nov 5th, 2008 at 4:05 pm.