如下所示,這是一個簡單的電腦:
#include<iostream>
#include<cstring>
using namespace std;
template <class T>
class stack
{
private:
int top;//棧頂
int maxtop;
T *st;//數組
public:
stack(int maxstacksize=10)
{
maxtop=maxstacksize-1;
st=new T[maxstacksize];
top=-1;
}
~stack()
{
delete [] st;
}
//判斷棧是否已滿
bool isfull()
{
return top==maxtop;
}
//判斷棧是否為空
bool isempty()
{
return top==-1;
}
//向棧頂添加元素
bool add(const T &x)
{
if(isfull())
{
cout<<"no memory"<<endl;
return false;
}
top++;
st[top]=x;
return true;
}
T del()//取出并删除元素
{
if(isempty())
{
cerr<<"no element"<<endl;
}
T x;
x=st[top];
top--;
return x;
}
//傳回棧頂元素值
T returntop()
{
return st[top];
}
//清空棧
void clear()
{
top=-1;
}
//輸出棧
void output()
{
if(isempty())
{
cout<<"棧是空的"<<endl;
}
else
{
for(int i=0;i<=top;i++)
{
cout<<st[i]<<'\t';
}
cout<<endl;
}
}
};
int main()
{
char math[20];
char fuhao[10]={0,0,0,0,0,0,0,0,0,0};
char shuzi[10]={'-','-','-','-','-','-','-','-','-','-'};
int number[10];
cout<<"輸入算數式,請以#結尾"<<endl;
cin>>math;
int j=0;
int p=0;
for(int i=0;i<20&&math[i]!='#';i++)
{
if(math[i]>=48&&math[i]<=57)
{
shuzi[j]=math[i];
j++;
}
else
{
fuhao[p]=math[i];
p++;
}
}
for(int i=0;i<20&&math[i]!='#';i++)
{
if(math[i]=='('&&i!=0)
{
if(math[i-1]>=48&&math[i-1]<=57)
{
cout<<"error"<<endl;
goto ending;
}
}
}
for(int i=0;i<10&&shuzi[i]!='-';i++)
{
number[i]=(int)shuzi[i]-48;
}
for(int i=0;i<10&&fuhao[i]!=0;i++)
{
if(fuhao[i]=='(')
{
int f=0;
for(int q=i;q<10&&fuhao[q]!=0;q++)
{
if (fuhao[q]==')')
{
f++;
}
}
if(f==0)
{
cout<<"表達式錯誤"<<endl;
goto ending;
}
}
}
return 0;
}