1 #include<iostream> 2 using namespace std; 3 double expr(char* str); 4 const int MAX=80; //待处理的最大字符串长度 5 void eatspace(char* str){ //去掉空格 6 int i=0; 7 int j=0; 8 while(str[i]!='\0') 9 if(str[i]==' '){ 10 i++; 11 } 12 else{ 13 str[j]=str[i]; 14 i++; 15 j++; 16 } 17 str[j]='\0'; 18 19 } 20 char* extract(char* str,int& index){ //返回括号之间的expr 21 int count=1; 22 char* substr=nullptr; 23 int substr_begin=index; 24 int substr_end=index; 25 char buffer[MAX]; 26 27 while(str[index]!='\0'){ 28 buffer[index-substr_begin]=str[index]; 29 30 switch(str[index++]){ 31 case '(': count++; break; 32 case ')': 33 count--; 34 substr_end=index-1; 35 int length=substr_end-substr_begin; 36 if(0==count){ 37 buffer[length]='\0'; 38 substr=new char[length+1]; 39 if(!substr){ 40 cout<<"Memory allocation failed,programme terminated!!"; 41 exit(1); 42 } 43 else{ 44 strcpy_s(substr,length+1,buffer); 45 return substr; 46 } 47 } 48 49 break; 50 } 51 } 52 if(count>0){ 53 cout<<endl<<"括号不匹配!!"<<endl; 54 exit(1); 55 } 56 57 58 59 } 60 double number(char* str,int& index){ //返回number 61 double value=0.0; 62 double factor=1.0; 63 if(str[index]=='('){ 64 char* psubstr=nullptr; 65 psubstr=extract(str,++index); 66 value=expr(psubstr); 67 delete[] psubstr; 68 psubstr=nullptr; 69 return value; 70 } 71 72 if(!isdigit(str[index])){ 73 cout<<endl<<"There is a number error!!!!!"<<endl; 74 exit(1); 75 } 76 while(isdigit(str[index])){ 77 value=10*value+(str[index++]-'0'); 78 } 79 if(str[index]!='.'){ 80 return value; 81 } 82 else{ 83 while(isdigit(str[++index])){ 84 factor*=0.1; 85 value+=(str[index]-'0')*factor; 86 } 87 } 88 89 return value; 90 91 } 92 double term(char* str,int& index){ //返回term 93 double value=0.0; 94 value=number(str,index); 95 96 while(true){ 97 switch(str[index++]){ 98 case '*': value*=number(str,index); break; 99 case '/': value-=number(str,index); break; 100 default: index--; return value; 101 } 102 } 103 104 } 105 double expr(char* str){ //返回expr 106 double value=0.0; 107 int index=0; 108 109 value=term(str,index); 110 while(true){ 111 switch(str[index++]){ 112 case '+': value+=term(str,index); break; 113 case '-': value-=term(str,index); break; 114 case '\0': return value; 115 default: cout<<endl<<"There is an expr error!!!!!!"<<endl; exit(1); 116 } 117 } 118 return value; 119 120 } 121 int main(void ){ 122 123 char buffer[MAX]; 124 cin.getline(buffer,MAX); 125 126 eatspace(buffer); 127 cout<<"After eaptspace:"<<endl; 128 for(int i=0;i<MAX;i++) 129 if(buffer[i]!='\0') 130 cout<<buffer[i]; 131 else 132 break; 133 134 cout<<"\t="<<expr(buffer)<<endl; 135 return 0; 136 }