标准C++算数表达式算法
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
string Postfix_Expression;
vector <double> StoreData;
vector <char> StoreOper;
vector <double> StoreQueue;
stack < double, vector<double> > Data_Stack(StoreData);
stack < char, vector<char> > Oper_Stack(StoreOper);
stack < double, vector<double> > Queue_Stack(StoreQueue);
inline int Priority( char );
void Make_The_Postfix_Stack();
void Calculate_The_Postfix_Stack();
int main(int argc, char * argv[])
{
Make_The_Postfix_Stack();
Calculate_The_Postfix_Stack();
system(\"pause\");
return 0;
}
void Make_The_Postfix_Stack()
{
size_t Index = 0;
string Scrstr;
string Buffer;
string Check(\".0123456789(+-*/)#\");
char Space;
char Char_Temp;
double Double_Temp;
Oper_Stack.push(’#’);
cout<<\"Please enter an expression:\"<<endl;
check1:
getline(cin, Scrstr);
if(Scrstr.find_first_not_of(Check,0) != string::npos)
{
cerr<<\"Error input, try again!\"<<endl;
goto
check1;
}
Scrstr += \"#\";
stringstream PushStream;
stringstream TempStream;
PushStream.str(Scrstr);
while( (PushStream.str().size() - Index) > 0 )
{
size_t StringSize;
[Page]
if(isdigit(PushStream.str()[Index]))
{
PushStream >> Double_Temp;
TempStream << Double_Temp;
TempStream >> Buffer;
StringSize = Buffer.size();
Index += StringSize;
Postfix_Expression = Postfix_Expression + \" \" + Buffer;
TempStream.clear();
}
else
{
PushStream >> Char_Temp;
switch(Char_Temp)
{
case ’(’:
Oper_Stack.push(Char_Temp);
break;
case ’)’:
case ’#’:
do{
Char_Temp = Oper_Stack.top();
Oper_Stack.pop();
if(Char_Temp != ’(’ && Char_Temp != ’#’)
Postfix_Expression = Postfix_Expression + \" \" + Char_Temp;
}while(Char_Temp!=’(’ && !Oper_Stack.empty());
break;
case ’+’:
case ’-’:
case ’*’:
case ’/’:
while(Priority(Char_Temp) <= Priority(Oper_Stack.top()))
{
Postfix_Expression = Postfix_Expression + \" \" + Oper_Stack.top();