Silver_Smoulder

[C++][Non-Func]Stacks

Apr 10th, 2019
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. //#define <stackinterface.h>
  5. #include <stack>
  6.  
  7. using namespace std;
  8.  
  9. int main ()
  10. {
  11. //declare variables
  12. char first, operand; //This will be storing the first entry from the string, and the second will be our operand.
  13. int test, size, var1, var2, result; //These will store our two integers and store it for output. Size is for our for loop terminator. Test is to hold a converted char-to-integer.
  14. string storage = ''; //This will be the user entry.
  15.  
  16. //user input
  17. cout << "Please input the postfix expression you want to evaluate: ";
  18. getline(cin, storage);
  19.  
  20. //We want to take the first character of the string, put it into first, then push it onto the stack.
  21. //When we hit the operand, we store it in operand variable, pop the first two entries of the stack into var1 and var 2.
  22. //Then we test if the stack is empty, if it isn't, we push them back onto the stack, and continue from the top.
  23.  
  24. stack = stack_1 //declare empty stack
  25. size = strlen.storage //define this as the size of our string in a separate int
  26. for (int i = 0; i <= size; i++){ //execute the loop until it reads the entire string
  27. first = storage.at(i) //put the first character of the string into the char variable first
  28. if (first != ('+' || '-' || '*' || '/' || '%') { //If they are not operands then do the following:
  29. test = atoi(first) //change the first character to an int
  30. stack_1.push(test); //push the int onto our stack
  31. else { //if it IS an operand
  32. var1 = stack_1.pop(); //pop off the top of the stack into the first var
  33. var2 = stack_1.pop(); //pop off the top of the stack (minus the previous one) into the second var
  34. switch //depending on the type of operand, perform the operation with <var2> <operand> <var1>
  35. case '+' :
  36. result = var2 + var1;
  37. case '-' :
  38. result = var2 - var1;
  39. case '*' :
  40. result = var2 * var1;
  41. case '/' :
  42. result = var2 / var1;
  43. case '%' :
  44. result = var2 % var1;
  45. }//At this point, we have iterated through the loop and either pushed all the values onto the stack or evaluated them all via our switch statement. I don't need to check whether the stack is empty or peek at it, because I know that I have reached the end of my string.
  46. cin.get();
  47. cin.get();
  48. return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment