初学C语言,大神帮忙给下思路。

算术表达式词法分析程序
1,从键盘输入一个表达式,如(23-(4*5.2-2.8))/-5;
2,支持+,-,*,/,()等符号。
3,支持运算符的优先级。
4,支持括号的嵌套。
5,要求将输入的算术表达式分解成一个个单词,如(,23,-,(,4,*,5.2,-,2.8,),),/,-5.

一般会先把中缀表达式转换为后缀表达式,然后再借助栈来处理。

http://download.csdn.net/download/perfeyfly/1924572

真的小白,已经琢磨一周了还是没有思路,下周要上交呢

#include

//#define MaxLen 100//存储空间

int tran(char str[], char expr[]) //将中缀表达式转换成后缀表达式 if(tran(str,expr)==0)//原来表达式,后缀表达式

{

int st[100]; //转化过程使用的过度栈

char ch;

int i=0,exindex=0,stindex=-1; //i是str下标,exindex是expr下标,stindex是st下标

while((ch=str[i++])!='\0')

{

if(ch>='0' && ch<='9') //判断是数字

{

expr[exindex]=ch; //压栈

exindex++; //栈顶指针上移

while((ch=str[i++])!='\0' && ch>='0' && ch<='9') //其它位依次入栈

{

expr[exindex]=ch; 

exindex++; 

}

i--; //str原算术表达式栈向下遍历

expr[exindex]='#'; //以特殊字符“#”表示结束

exindex++;

}

 else if(ch=='(')   //判断为左括号 

{

stindex++;

st[stindex]=ch;

}

 else if(ch==')')    //判断为右括号 

{

while (st[stindex]!='(')

{

expr[exindex]=st[stindex]; 

stindex--;   //依次弹出 

exindex++; 

}

stindex--;//'('出栈

}

 else if(ch=='+' || ch=='-')//判断为加减号 

{

while(stindex>=0 && st[stindex]!='(')

{

expr[exindex]=st[stindex]; 

stindex--; 

exindex++; 

}

stindex++;

st[stindex]=ch;

}

 else if (ch=='*' || ch=='/')//判断为乘除号 

{

while(st[stindex]=='*' || st[stindex]=='/')

{

expr[exindex]=st[stindex]; 

stindex--; 

exindex++; 

}

stindex++;

st[stindex]=ch;

}

}

while (stindex>=0)//将栈中所有运算符依次弹出存入expr栈中

{

expr[exindex]=st[stindex];

exindex++;

stindex--;

}

expr[exindex]='\0';

return 1;

}

int compvalue(char expr[],int *n)

{

int st[100],d; //st为数栈

char ch;

int exindex=0,stindex=-1; //exindex是expr下标,stindex是st的下标

while((ch=expr[exindex++])!='\0')

{

if(ch>='0'&&ch<='9')//将数字字符转换成数字

{

d=0;

do

{

d=10*d+ch-'0';     

}

while((ch=expr[exindex++])!='#');

stindex++;

st[stindex]=d;//数字进栈

}

else//运算符操作

{

switch(ch)

{

case'+':st[stindex-1]=st[stindex-1]+st[stindex];

break; 

case'-':st[stindex-1]=st[stindex-1]-st[stindex];

break; 

case'*':st[stindex-1]=st[stindex-1]*st[stindex];

break; 

case'/':

if(st[stindex]!=0) 

{ st[stindex-1]=st[stindex-1]/st[stindex]; } 

else return 0;  //除0错误! 

break; 

}

stindex--;

}

}

(*n)=st[stindex];

return 1;

}

void main()

{

char str[100]; //存储原来算术表达式

char expr[100]; //存储转换成的后缀表达式

int n;

cout<<"输入算术表达式:"<<endl;

cin>>str;

if(tran(str,expr)==0)

{

cout<<"原算术表达式不正确!"<<endl;

}

else

{

cout<<"转换成后缀表达式输出:"<<endl<<expr<<endl;

if(compvalue(expr,&n)==1)

{

cout<<"表达式求值:"<<endl<<n<<endl;

}

else

{

cout<<"计算错误!"<<endl;

}


}