#include <iostream>
#include <string>
using namespace std;
int find_parenthese(string operations_A,int index_top){
while(operations_A[index_top]!=')'){
if(index_top>operations_A.length()){
break;
}
if(operations_A[index_top]=='('){
index_top=find_parenthese(operations_A,index_top+1);
}
index_top++;
}
return index_top;
}
int Arithmetic(string operations,int index_top,int index_end){
bool c=0;
int value_1=0,value_2=1,operand=0,score;
for(int i=index_top;i<index_end;i++){
if(operations[i]!=' '){
if(operations[i]>48 && operations[i]<=57){
score=0;
for(i;i<index_end;i++){
if(operations[i]>=48 && operations[i]<=57){
score=score*10+operations[i]-48;
}else{
break;
}
}
i--;
if(operand==0){
value_2*=score;
}else if(operand==1){
value_2/=score;
}else{
value_2%=score;
}
c=1;
}else if(operations[i]=='+'){
value_1+=value_2;
value_2=1;
operand=0;
c=0;
}else if(operations[i]=='-'){
value_1+=value_2;
value_2=-1;
operand=0;
c=0;
}else if(operations[i]=='*'){
operand=0;
}else if(operations[i]=='/'){
operand=1;
}else if(operations[i]=='%'){
operand=2;
}else if(operations[i]=='('){
if(operand==0){
value_2*=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
}else if(operand==1){
value_2/=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
}else{
value_2%=Arithmetic(operations,i+1,find_parenthese(operations,i+1)+1);
}
i=find_parenthese(operations,i+1);
c=1;
}
}
if(i==index_end-1 && c==1){
value_1+=value_2;
}
}
return value_1;
}
int main()
{
cout<<"輸入資料若干行直到 EOF 為止。每一行包含輸入一個字串,其中包含運算元及運算子,為了方便讀取,所有的運算子及運算元均以空格區隔。\n";
cout<<"運算元為 0 ~231 -1 的整數\n運算子則包含 + - * / % 及 ( )\n運算時請注意先乘除後加減及() 優先運算的計算規則\n";
string input_operations;
while(true){
cout<<"請輸入運算式:";
getline(cin,input_operations);
cout<<input_operations<<"的運算結果為:"<<Arithmetic(input_operations,0,input_operations.length())<<endl;
}
return 0;
}