⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 porland.cpp

📁 逆波蓝式转换小程序 逆波蓝式转换小程序
💻 CPP
字号:
#include <stack>
#include <algorithm>
#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
using boost::shared_ptr;

struct Exp;
struct Item{
    char  number;
    shared_ptr<Exp> pExp;
    bool isNumber;
	explicit Item():isNumber(true), number('0'), pExp(){	}
	Item(const Item& i):number(i.number), pExp(i.pExp), isNumber(i.isNumber){ }
};

struct Exp{
    char  op;
    Item  lhs;
    Item  rhs;
	Exp(){};
	Exp(char _op, Item _lhs, Item _rhs):op(_op), lhs(_lhs), rhs(_rhs){ }
	Exp(const Exp& e):op(e.op), lhs(e.lhs), rhs(e.rhs) { }
};

class Error{
    string info;
public:
    Error(string _info):info(_info){ }
    Error():info(""){ }
    string what(){return info;}   
};

void printPorland(Exp& exp){
	cout << exp.op ;
	if(exp.lhs.isNumber)  cout << exp.lhs.number;
	else printPorland(*exp.lhs.pExp);
	if(exp.rhs.isNumber)  cout << exp.rhs.number;
	else printPorland(*exp.rhs.pExp);
	return;
}

int main()
{
    stack<Item>  ExpStack;
    char tmpChar;
    Item tmpItem;
    Item tmpLhs;
    Item tmpRhs;
    string  numbers = "0123456789";
    string  operators = "+-*/";

    cout<<"Input the Express(输入 'e'标识结束):";
	do{
	try{
		while(cin>>tmpChar){
			if(tmpChar == 'e') break;  //e为结束符
			else if(find(numbers.begin(), numbers.end(),  //是一个数字
					tmpChar)!=numbers.end()){
				tmpItem.isNumber = true;
				tmpItem.number   = tmpChar;
				ExpStack.push(tmpItem);//数字入栈

			}else if(find(operators.begin(), operators.end(), //是一个操作符
					tmpChar)!=operators.end()){
				//操作符每次要对应两个被操作数,否则语法错误
				if(ExpStack.size()<2) throw Error("Syntactic Error!"); 

				//操作符两边的元素出栈
				tmpRhs = ExpStack.top();
				ExpStack.pop();
				tmpLhs = ExpStack.top();
				ExpStack.pop();

				tmpItem.isNumber = false;   //非数字,是一个表达式
				tmpItem.pExp = shared_ptr<Exp>(new Exp(tmpChar, tmpLhs, tmpRhs)); 

				ExpStack.push(tmpItem);     //表达式入栈
	                       
			}else {  // 未知字符
				throw  Error("Unknow Character!");
			}
		}

		if(ExpStack.size()!=1) throw Error("Syntactic Error!");

		tmpItem = ExpStack.top();
		ExpStack.pop();

		if(tmpItem.isNumber) cout << tmpItem.number <<endl;
		else printPorland(*tmpItem.pExp);
		cout << endl;

	}catch(Error& e){
        cout << e.what() << endl;
		getline(cin, string());		//跳过错误的当前行
    }

		cout << "Try again?(y/n)" << endl;
		cin >> tmpChar;
	}while(tmpChar == 'y' || tmpChar == 'Y');
    
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -