Order of operations!

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Reply

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

Order of operations!

 
0
  #1
Nov 6th, 2008
I'm writing a function parser, which (hopefully) will be able to handle much more complex problems than basic operations. I've just completed the handling of the addition, subtraction, and brackets, but am at a loss of how to implement proper order of operations for multiplication and division. In order to make them work correctly, they must first be put in brackets. ie 2 + 4 * 3 outputs 18 instead of 14, but 2 + (4 * 3) outputs 14.

I've thought of just adding brackets to the function to force order of operations, but that seems more like a band-aid than an actual fix. Heres the code:

Header:

  1. #pragma once
  2. #pragma warning(disable: 4018)
  3. #include <iostream>
  4. #include <string.h>
  5. using namespace std;
  6.  
  7. class CFunction
  8. {
  9. protected:
  10. string _sFunc;
  11. int _iCursor;
  12. int GetNextValue(int &);
  13. char GetNextOp(int &);
  14. string ToCloseBracket(int &);
  15. public:
  16. bool SetFunc(string);
  17. int Solve(char = 0);
  18. //inline ctor
  19. CFunction(string s): _iCursor(0)
  20. {
  21. int iO(0),iC(0);
  22. for (int i(0); i < strlen(s.c_str()); ++i)
  23. {
  24. if (s[i] == '(')
  25. iO++;
  26. else if (s[i] == ')')
  27. iC++;
  28. }
  29. if (iO != iC)
  30. throw exception ("Bracket Error");
  31. _sFunc = s;
  32. }
  33. ~CFunction(void);
  34. };

class cpp file:

  1. #include "Function.h"
  2.  
  3.  
  4. CFunction::~CFunction(void)
  5. {
  6. }
  7.  
  8. int CFunction::GetNextValue(int & i)
  9. {
  10. string sBuffer;
  11. char szFormula[255];
  12. strcpy_s(szFormula, 255, _sFunc.c_str());
  13. bool numStream(false);
  14. for (i = i; i < strlen(szFormula); ++i)
  15. {
  16. if (isdigit(szFormula[i]))
  17. {
  18. //add the digit to the buffer
  19. numStream = true;
  20. sBuffer += szFormula[i];
  21. }
  22. if (numStream && (!isdigit(szFormula[i]) || i == strlen(szFormula) - 1))
  23. {
  24. return atoi(sBuffer.c_str()); //return the buffer, converted to int
  25. }
  26. if (szFormula[i] == '(')
  27. {//solve what's inside brackets first!
  28. string tmp(ToCloseBracket(i));
  29. return CFunction(tmp).Solve();
  30. }
  31. }
  32. //error flag
  33. return -1;
  34. }
  35.  
  36. string CFunction::ToCloseBracket(int & iIndex)
  37. {
  38. string sBuffer = "";
  39. int iCount(0), iCount2(0);
  40. int iOIndex(iIndex), iCIndex(iIndex + 1);
  41. for (iCIndex; iCIndex < strlen(_sFunc.c_str()); ++iCIndex)
  42. {
  43. if (_sFunc[iCIndex] == '(')
  44. iCount++;
  45. if (_sFunc[iCIndex] == ')' && iCount == 0)
  46. break;
  47. if (_sFunc[iCIndex] == ')')
  48. iCount--;
  49. }
  50. for (iIndex++; iIndex < iCIndex; iIndex++)
  51. sBuffer += _sFunc[iIndex];
  52. return sBuffer;
  53. }
  54.  
  55. int CFunction::Solve(char var)
  56. {
  57. if (strlen(_sFunc.c_str()) < 1)
  58. throw exception ("Invalid Function");
  59. int i(0),
  60. iTmpVal(0),
  61. iReturn(0);
  62. char op(0);
  63. iReturn = GetNextValue(i);
  64. while (i < strlen(_sFunc.c_str()) - 1)
  65. {
  66. op = GetNextOp(i);
  67. iTmpVal = GetNextValue(i);
  68. switch (op)
  69. {
  70. case '+': iReturn += iTmpVal; break;
  71. case '-': iReturn -= iTmpVal; break;
  72. case '*': iReturn *= iTmpVal; break;
  73. case '/': if (iTmpVal != 0) iReturn /= iTmpVal; else throw exception("Division By Zero"); break;
  74. default: break;
  75. }
  76. }
  77. return iReturn;
  78. }
  79.  
  80. char CFunction::GetNextOp(int & i)
  81. {
  82. for (i; i < strlen(_sFunc.c_str()); ++i)
  83. if (_sFunc[i] == '+' || _sFunc[i] == '-' || _sFunc[i] == '*' || _sFunc[i] == '/')
  84. return _sFunc[i];
  85. //error flag
  86. return -1;
  87. }

Sample implementation in main()

  1. #include <string>
  2. #include <iostream>
  3. using namespace std;
  4. #include "Function.h"
  5.  
  6. int main()
  7. {
  8. char szBuffer[255];
  9. string sBuffer = "";
  10. for (int i(0); i < 5; ++i)
  11. {
  12. cin.ignore(cin.rdbuf()->in_avail());
  13. cout << "Enter formula: ";
  14. cin.getline(szBuffer, 254);
  15. sBuffer = szBuffer;
  16. CFunction myFunc(sBuffer);
  17. int ii(0);
  18. try
  19. {
  20. if ((ii = myFunc.Solve()) == -1)
  21. throw exception("Unknown Error");
  22. cout << sBuffer << " = " << ii;
  23. }
  24. catch (exception exc)
  25. {
  26. cout << "Error Encountered while solving for " << sBuffer;
  27. cout << "\nType: " << exc.what();
  28. }
  29. cin.get();
  30. }
  31. return 0;
  32. }

Any pointers in the right direction would be greatly appreciated!
Last edited by skatamatic; Nov 6th, 2008 at 7:28 pm.
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 2,001
Reputation: ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of 
Solved Threads: 343
ArkM's Avatar
ArkM ArkM is offline Offline
Postaholic

Re: Order of operations!

 
0
  #2
Nov 6th, 2008
Have you ever search INET for arithmetic expressions parsing&evaluation?
Try that, there are lots of info and codes on this old good topic...
Last edited by ArkM; Nov 6th, 2008 at 7:41 pm.
Reply With Quote Quick reply to this message  
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: Order of operations!

 
0
  #3
Nov 6th, 2008
Originally Posted by ArkM View Post
Have you ever search INET for arithmetic expressions parsing&evaluation?
Try that, there are lots of info and codes on this old good topic...
Hmm well from what a google search turned up, I got a bunch of libraries and dlls that will do parsing for me, but I want to write the actual parser! Not many of them seem to be open source, but I'll keep looking. thanks. Perhaps post a more direct link, since a lot of companies/websites seem to have the word INET in it .
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 2,056
Reputation: ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of 
Solved Threads: 312
ddanbe's Avatar
ddanbe ddanbe is online now Online
Postaholic

Re: Order of operations!

 
0
  #4
Nov 6th, 2008
Also try to read and understand a recursive descent parser : http://en.wikipedia.org/wiki/Recursive_descent_parser
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Reply With Quote Quick reply to this message  
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: Order of operations!

 
0
  #5
Nov 6th, 2008
Originally Posted by ddanbe View Post
Also try to read and understand a recursive descent parser : http://en.wikipedia.org/wiki/Recursive_descent_parser
Yikes. I'm not afraid of C but that program is a bit beyond me. Although I think I'm on the right track, in that I'm recursively solving the brackets until the most simplified possible expression can be solved by basic operations. Correct me if I'm wrong, but I think this could be considered a recursive descending parser. Thanks for the link btw.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 2,056
Reputation: ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of 
Solved Threads: 312
ddanbe's Avatar
ddanbe ddanbe is online now Online
Postaholic

Re: Order of operations!

 
1
  #6
Nov 12th, 2008
Hey Skatamatic, Right now I'm into C# for that matter and I have been in BASIC, Pascal,Modula-2,C,C++. So the language is not that much of an issue.
Look at this compilercode from a master :
http://www.246.dk/pl0.html
For the moment I am trying to translate in C# the code for the calculator in Bjarne Stroustrup's book: "The C++ PROGRAMMING LANGUAGE"
Maybe we can exchange codes?
Last edited by ddanbe; Nov 12th, 2008 at 5:23 pm.
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Reply With Quote Quick reply to this message  
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: Order of operations!

 
0
  #7
Nov 12th, 2008
Originally Posted by ddanbe View Post
Hey Skatamatic, Right now I'm into C# for that matter and I have been in BASIC, Pascal,Modula-2,C,C++. So the language is not that much of an issue.
Look at this compilercode from a master :
http://www.246.dk/pl0.html
That, again, is quite the code! I'm not too sure of the language, I'm only really fluent with C++, SQL, basic assembly, and QBasic, but it's still somewhat readable. I'm not too sure of it's functionality though; this looks like a complete compiler, yet I can't seem to find where it converts its data into opcodes/assembly language. I'll keep trying to make some sense of it! Thanks.
Reply With Quote Quick reply to this message  
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: Order of operations!

 
0
  #8
Nov 12th, 2008
Originally Posted by ddanbe View Post
Hey Skatamatic, Right now I'm into C# for that matter and I have been in BASIC, Pascal,Modula-2,C,C++. So the language is not that much of an issue.
Look at this compilercode from a master :
http://www.246.dk/pl0.html
For the moment I am trying to translate in C# the code for the calculator in Bjarne Stroustrup's book: "The C++ PROGRAMMING LANGUAGE"
Maybe we can exchange codes?
Sounds good. Is there a link to this calculator's specifications?
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 2,001
Reputation: ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of 
Solved Threads: 343
ArkM's Avatar
ArkM ArkM is offline Offline
Postaholic

Re: Order of operations!

 
0
  #9
Nov 12th, 2008
Originally Posted by skatamatic View Post
Hmm well from what a google search turned up, I got a bunch of libraries and dlls that will do parsing for me, but I want to write the actual parser! Not many of them seem to be open source, but I'll keep looking. thanks. Perhaps post a more direct link, since a lot of companies/websites seem to have the word INET in it .
That's not the point to get "a buch of libraries and dlls that will do parsing for me" (all dlls are libraries too ) though open source parsing codes are excellent text-books and primers per se. There lots of text-books and articles on this topic too.

Don't search word INET: INET means Internet, that's all. If you want direct links - for example, download compact and well-written book "Parsing Techniques - A Practical Guide" from http://www.cs.vu.nl/~dick/PTAPG.html.

Don't invent square wheels...
Reply With Quote Quick reply to this message  
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: Order of operations!

 
0
  #10
Nov 12th, 2008
Originally Posted by ArkM View Post
That's not the point to get "a buch of libraries and dlls that will do parsing for me" (all dlls are libraries too ) though open source parsing codes are excellent text-books and primers per se. There lots of text-books and articles on this topic too.

Don't search word INET: INET means Internet, that's all. If you want direct links - for example, download compact and well-written book "Parsing Techniques - A Practical Guide" from http://www.cs.vu.nl/~dick/PTAPG.html.

Don't invent square wheels...
Lol. I feel like an idiot (inet ). And there's nothing wrong with reinventing square wheels if it further helps me understand parsing techniques!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 1846 | Replies: 9
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC