아래의 소스는 http://www.fredosaurus.com/notes-cpp/examples/rpn/rpn.html 에
올려져 있는 그대로의 (명령행 RPN 계산기) C++ 소스입니다.
소스가 매우 간단하다.
그러나 부족한 점이 몇 가지 눈에 띤다.
1) 소수점 있는 수를 처리하지 못한다.
2) 음수를 피연산자로 쓸 수 없다.
3) 기타
이런 점을 개선한 소스는 http://www.scripts.pe.kr/wiki/wiki.php/RPNCalc 에서 볼 수 있다.
// Fred Swartz 2001-12-05, 2002-09-27
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
int pop(vector<int>& stk); //--- prototype to pop stack
//============================================================= main
int main() {
vector<int> opndStack; // vector used as operand stack
string token; // to read number or operator
while (cin >> token) {
if (isdigit(token[0])) { // if first is digit, it's number.
opndStack.push_back(atoi(token.c_str())); // convert, push
} else { // If it's not a number, assume it's an operator
int left, right; // used by some operators as temps
switch (token[0]) { // assume operators are one char
case '+': opndStack.push_back(pop(opndStack) + pop(opndStack));
break;
case '-': right = pop(opndStack); // get right operand
left = pop(opndStack); // get left operand
opndStack.push_back(left - right);
break;
case '*': opndStack.push_back(pop(opndStack) * pop(opndStack));
break;
case '/': right = pop(opndStack); // get right operand
left = pop(opndStack); // get left operand
opndStack.push_back(left / right);
break;
default: throw domain_error("Undefined operator");
}
cout << "Result: " << opndStack.back() << endl;
}
}
return 0;
}//end main
//============================================================== pop
// This utility function checks stack for underflow
// and pops (removes and returns) last element.
int pop(vector<int>& stk) {
if (stk.empty()) {
throw underflow_error("Stack underflow.");
}
int result = stk.back();
stk.pop_back();
return result;
}//end pop
'프로그래밍 > C++' 카테고리의 다른 글
스트링 배열 정렬(sorting)하기 with C++ STL (0) | 2009.04.20 |
---|---|
손으로 계산하는 긴자리 곱셈표 만들기 with C++ (0) | 2009.03.07 |
C/C++ 프로그래밍 추천 사이트 (0) | 2009.02.07 |
손으로 만드는 나눗셈 계산표 with C++ (0) | 2008.05.16 |
클래스 상속(subclassing) 예제 with C++ (0) | 2008.04.05 |