View Single Post
Join Date: Nov 2007
Posts: 390
Reputation: skatamatic will become famous soon enough skatamatic will become famous soon enough 
Solved Threads: 39
skatamatic skatamatic is offline Offline
Posting Whiz

Re: CIN>>EQUATION (how to then mult by it later)

 
0
  #9
Nov 5th, 2008
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.

  1. #include <string.h>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. string sFormula = "";
  7. string sBuffer;
  8. char szFormula[255];
  9. bool numStream(false);
  10. int iVal[2] = {0};
  11. int iReturnVal(0);
  12. int iCount(0);
  13. char cLastOperator(0);
  14. cout << "Enter formula: ";
  15. cin.getline(szFormula, 54);
  16. for (unsigned int i(0); i < strlen(szFormula); ++i)
  17. {
  18. if (isdigit(szFormula[i]))
  19. {
  20. numStream = true;
  21. sBuffer += szFormula[i];
  22. }
  23. if (numStream && (!isdigit(szFormula[i]) || i == strlen(szFormula) - 1))
  24. {
  25. numStream = false;
  26. iVal[iCount++] = atoi(sBuffer.c_str());
  27. if (cLastOperator == '+')
  28. {
  29. iReturnVal += iVal[0] + iVal[1];
  30. iVal[0] = 0;
  31. iVal[1] = 0;
  32. iCount = 0;
  33. cLastOperator = 0;
  34. }
  35. else if (cLastOperator == '-')
  36. {
  37. iReturnVal -= iVal[0] + iVal[1];
  38. iVal[0] = 0;
  39. iVal[1] = 0;
  40. iCount = 0;
  41. cLastOperator = 0;
  42. }
  43. sBuffer = "";
  44. }
  45. if (!numStream && (szFormula[i] == '+' || szFormula[i] == '-' || szFormula[i] == '*'))
  46. {
  47. cLastOperator = szFormula[i];
  48. }
  49. }
  50. cout << szFormula << " = " << iReturnVal << endl;
  51. cin.get();
  52. return 0;
  53. }

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.
Reply With Quote