Silver_Smoulder icon

[C++][Non-Func]Stacks

Silver_Smoulder | PRO | 04/10/19 06:51:44 PM UTC | 0 ⭐ | 433 👁️ | Never ⏰ | []
text |

2.3 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <cstdlib>
#include <cstring>
//#define <stackinterface.h>
#include <stack>
 using namespace std;
 int main ()
{
	//declare variables
	char first, operand; //This will be storing the first entry from the string, and the second will be our operand.
	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.
	string storage = ''; //This will be the user entry.
 	//user input
	cout << "Please input the postfix expression you want to evaluate: ";
	getline(cin, storage);
 	//We want to take the first character of the string, put it into first, then push it onto the stack.
	//When we hit the operand, we store it in operand variable, pop the first two entries of the stack into var1 and var 2.
	//Then we test if the stack is empty, if it isn't, we push them back onto the stack, and continue from the top.
 	stack = stack_1 //declare empty stack
	size = strlen.storage //define this as the size of our string in a separate int
	for (int i = 0; i <= size; i++){ //execute the loop until it reads the entire string
		first = storage.at(i) //put the first character of the string into the char variable first
		if (first != ('+' || '-' || '*' || '/' || '%') { //If they are not operands then do the following:
			test = atoi(first) //change the first character to an int
			stack_1.push(test); //push the int onto our stack
		else { //if it IS an operand
			var1 = stack_1.pop(); //pop off the top of the stack into the first var
			var2 = stack_1.pop(); //pop off the top of the stack (minus the previous one) into the second var
			switch //depending on the type of operand, perform the operation with <var2> <operand> <var1>
				case '+' :
					result = var2 + var1;
				case '-' :
					result = var2 - var1;
				case '*' :
					result = var2 * var1;
				case '/' :
					result = var2 / var1;
				case '%' :
					result = var2 % var1;
			}//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.
	cin.get();
	cin.get();
	return 0;
}

Comments