본문 바로가기

컴퓨터/C++

Stack을 이용한 간단한 계산기

반응형
#include <iostream>
#include <string>
#include <sstream>
#include <stack>

using namespace std;

int calc(int op1, int op2, string op){
	if(!op.compare("+")){
		return op1+op2;
	}
	if(!op.compare("-")){
		return op1-op2;
	}
	if(!op.compare("*")){
		return op1*op2;
	}
	if(!op.compare("/")){
		return op1/op2;
	}
	cout << "ERROR!";
	return -1;
}

int main() {
	// your code goes here
	stack<string> stack;
	string str = string("( ( ( 2 * 5 ) - ( 1 * 2 ) ) / ( 11 - 9 ) ) \n");
	stringstream stream(str);
	string token;
	
	while (stream >> token){
		cout << token << " ";
		if(!token.compare(")")){
			int op2 = stoi(stack.top());
			stack.pop();
			string op = stack.top();
			stack.pop();
			int op1 = stoi(stack.top());
			stack.pop();
			stack.pop();
			stack.push(to_string(calc(op1, op2, op)));
			continue;
		}
		stack.push(token);
	}
	cout << endl << "Result : " << stack.top();
	
	return 0;
}
반응형

'컴퓨터 > C++' 카테고리의 다른 글

complex class 구현  (0) 2016.04.27
대소문자 변경하기  (0) 2016.04.18
Merge Sort 구현  (0) 2016.04.17
*없이 두 정수 곱하기  (0) 2016.04.13
Stack 기반 미로 찾기(DFS)  (0) 2015.10.27