#include <iostream>
#include <vector>
#include <stack>
#include <ctype.h>
#include <cstdlib>
#include <sstream>
using
namespace
std;
bool
IsDigit(string str)
{
for
(
int
i = 0; i < str.size(); i++)
if
((str.at(i) >
‘9‘
) || (str.at(i) <
‘0‘
))
return
false
;
return
true
;
}
int
main()
{
stack<string> s;
string input;
while
(cin >> input)
{
if
(IsDigit(input))
s.push(input);
else
if
((input ==
"+"
) || (input ==
"-"
) || (input ==
"*"
) || (input ==
"/"
))
{
int
lhs =
atoi
((s.top()).c_str());
s.pop();
int
rhs =
atoi
((s.top()).c_str());
s.pop();
stringstream ss;
string midval;
switch
(*input.c_str())
{
case
‘+‘
:
ss << (lhs+rhs);
ss >> midval;
s.push(midval);
break
;
case
‘-‘
:
ss << (lhs-rhs);
ss >> midval;
s.push(midval);
break
;
case
‘*‘
:
ss << (lhs*rhs);
ss >> midval;
s.push(midval);
break
;
case
‘/‘
:
ss << (rhs/lhs);
// 注意除法的操作数有顺序限制
ss >> midval;
s.push(midval);
break
;
}
}
}
cout << s.top();
return
0;
}
原文地址:http://blog.csdn.net/nestler/article/details/24664563