どうもtakazinです。
buf="5 55 33 999 1234+ * /- 77 44+ - 999+ 888+ 555+ 444- 333- 222- 121 131 + -"
//buf="3 4 5+-"
sdim buf_,1024
sdim tmp,256,1024
sdim tmp_op,256,1024
dim op,1024
sdim tmp1,1024
sdim tmp2,1024
index=0
sp=0
while(1)
if(index>=strlen(buf)):_break
data=peek(buf,index)
if(limit(data,'0','9')==data){
tmp(sp)=""
while(1)
if(index>=strlen(buf)):_break
data=peek(buf,index)
if(limit(data,'0','9')!=data):_break
tmp(sp)+=strf("%c",data)
index++
wend
sp++
}
if(data=='+'|data=='-'|data=='*'|data=='/'){
tmp(sp)=strf("%c",data)
op(sp)=1 //演算子なら真
index++
sp++
}
if(data==' '|data=='\t'|data==0x0D|data=0x0A){
index++
}
wend
spmax=sp
index=0
sp=0
while(1)
if(spmax<sp):_break
if(op(sp)==1){
sp_=sp
takou1=0
takou2=0
while(1)
if(op(sp_)==0){
tmp1=tmp(sp_)
op(sp_)=3
_break
}
if(op(sp_)==2){
tmp1=tmp(sp_)
op(sp_)=3
takou1=1
takou1_sp=sp_
_break
}
sp_--
if(sp_<0){
mes "オペランドの数が合いません"
stop
}
wend
while(1)
if(op(sp_)==0){
tmp2=tmp(sp_)
op(sp_)=2
_break
}
if(op(sp_)==2){
tmp2=tmp(sp_)
op(sp_)=2
takou2=1
takou2_sp=sp_
_break
}
sp_--
if(sp_<0){
mes "オペランドの数が合いません"
stop
}
wend
tmp1_=tmp1
tmp2_=tmp2
if(takou1==1){
if((tmp(sp)=="*"||tmp(sp)=="/")&&(tmp_op(takou1_sp)=="+"||tmp_op(takou1_sp)=="-")){
tmp1_="("+tmp1+")"
}
if((tmp(sp)=="/")&&(tmp_op(takou1_sp)=="*")){
tmp1_="("+tmp1+")"
}
if((tmp(sp)=="-")&&(tmp_op(takou1_sp)=="+"||tmp_op(takou1_sp)=="-")){
tmp1_="("+tmp1+")"
}
if((tmp(sp)=="+")&&(tmp_op(takou1_sp)=="+"||tmp_op(takou1_sp)=="-")){
tmp1_=tmp1
}
}
if(takou2==1){
if((tmp(sp)=="*"||tmp(sp)=="/")&&(tmp_op(takou2_sp)=="+"||tmp_op(takou2_sp)=="-")){
tmp2_="("+tmp2+")"
}
if((tmp(sp)=="-")&&(tmp_op(takou2_sp)=="+"||tmp_op(takou2_sp)=="-")){
tmp2_=tmp2
}
if((tmp(sp)=="+")&&(tmp_op(takou2_sp)=="+"||tmp_op(takou2_sp)=="-")){
tmp2_=tmp2
}
}
tmp(sp_)=tmp2_+tmp(sp)+tmp1_
tmp_op(sp_)=tmp(sp)
buf_=tmp2_+tmp(sp)+tmp1_
}
sp++
wend
mes buf
mes buf_
かなり“クセ”のあるコードですが何とか解読してください^^;
1 2 + 5*
5 1 2 + *
3 4 5+-
をちゃんと
(1+2)*5
5*(1+2)
3-(4+5)
のように正しく括弧をつけることだできます。
サンプルでは演算子優先順位を”なんちゃって”判定しているので無駄な括弧は生成されません
↓このように
5-55/(33*(999+1234))-(77+44)+999+888+555-444-333-222-(121+131)
しかしその処理を端折っても一応 中置記法には変換できます(見栄えは悪いですが)
↓このように
(((((((((5-(55/(33*(999+1234))))-(77+44))+999)+888)+555)-444)-333)-222)-(121+131))
がんばってください。