可以区分括号,能够计算多位的数字
#include <iostream>
#include <stack>
#include <sstream>
#include <cctype>
//#include <cmath>
class in2pocal
{
private:
int level0fop(char op) {
if (op == '*' || op == '/')
return 2;
else if (op == '+' || op == '-')
return 1;
return 0;
}
bool isop(char ch){
return ch == '+'||ch == '-'||ch == '*'||ch == '/';
}
//bool isnum(char ch);不需要这个,头文件里面有现成的
public:
std::string in2po(const std::string& infix);
};
std::string in2pocal::in2po(const std::string& infix){
std::stringstream postfix;//字符串流
std::stack<char> operators;//定义一个承载char类型数据的栈
bool preisnum = false;
for (char ch : infix)
{
if (std::isalnum(ch))
{
if (preisnum)
{
postfix << ch;
}else {
postfix << ' ' << ch;
preisnum = true;
}
}else if (ch == '(')
{
operators.push(ch);
preisnum = false;
}else if (ch == ')')
{
while (!operators.empty() && operators.top() != '(')
{
postfix << ' ' << operators.top();//返回栈顶元素
operators.pop();
}
if (!operators.empty() && operators.top() == '(')
{
operators.pop();
}
preisnum = false;
}else if (isop(ch))
{
while (!operators.empty() && (level0fop(operators.top()) > isop(ch)))
{
postfix << ' ' << operators.top();
operators.pop();
}
operators.push(ch);
preisnum = false;
}
}
while (!operators.empty()) {
postfix << ' ' << operators.top();
operators.pop();
}
return postfix.str();
}
/* int main() {
in2pocal converter;
std::string infixExpression;
std::cout << "Enter infix expression: ";
std::getline(std::cin, infixExpression);
std::string postfixExpression = converter.in2po(infixExpression);
std::cout << "Postfix expression: " << postfixExpression << std::endl;
}
*/
#include "in2pocal.h"
int evaluatePostfix(const std::string& postfix) {
std::stack<int> operands;
bool preisnum = false;
for (char ch : postfix) {
if (std::isdigit(ch)) {
// 如果是数字,将其转换为整数并压入栈
int digit = ch - '0';
if (preisnum) {
digit = operands.top()*10 + digit;
operands.pop();
operands.push(digit);
}else{
operands.push(digit);
preisnum = true;
}
}else if (ch != ' ') {
// 如果是运算符,弹出两个操作数并执行相应的操作
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
switch (ch) {
case '+':
operands.push(operand1 + operand2);
break;
case '-':
operands.push(operand1 - operand2);
break;
case '*':
operands.push(operand1 * operand2);
break;
case '/':
operands.push(operand1 / operand2);
break;
default:
std::cerr << "Invalid character in postfix expression: " << ch << std::endl;
return -1; // 错误情况
}
}else if (ch == ' ')
{
preisnum = false;
continue;
}
}
// 栈顶元素即为计算结果
return operands.top();
}
int main() {
in2pocal converter;
std::string infixExpression;
std::getline(std::cin, infixExpression);
std::string postfixExpression = converter.in2po(infixExpression);
int result = evaluatePostfix(postfixExpression);
std::cout << "Result: " << result << std::endl;
return 0;
}