a,b,c,d 와 사칙연산(+,-,*,/) 그리고 괄호가 포함된 수식을 파싱(파서~)하는 소스입니다. 책도 안보고 제 멋대로 맹근건데 오류는 없는듯 합니다. 혹, 오류가 있으면 이곳에 올려주세요.^.^(관련글 적기로...)
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_ // Korea Maritime Univ. Div. Automation & Information. /_ // Major. Computer Engineering. /_ // 9727052 Lee Gun-woo. ([email protected]) /_ // Parsing Source. /_ //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_ #include
int fTrashBlank(char Op[100], char Ops[100])
{
int iCount=0, iCount2=0;
do{
if(Op[iCount] != ' '){
Ops[iCount2] = Op[iCount];
iCount2++;
}
iCount++;
if(iCount > 99) break;
}while(Op[iCount] != NULL);
return iCount2;
}
int fChkToken(char Op[100])
{
int iChkBeforeToken, // 0 - a,b,c,d,( | 1 - +,-,*,/,(
iChkC, //괄호의 열고 닫힘 여부
iChkCcount, //열린 괄호의 카운트
iTokenCount, //총 토큰 카운트
iCharCount, //문자 카운트
ii;
char cOperation[100];
iTokenCount = ( fTrashBlank(Op, cOperation) - 1); //공백제거 후 총 토큰수 리턴
iChkBeforeToken = 0;
iChkC = 0;
iChkCcount = 0;
iCharCount = 0;
for(ii=0;ii<=iTokenCount;ii++){
switch(cOperation[ii]){
case '+':
case '-':
case '*':
case '/':
case ')':
if(iChkBeforeToken == 0) return 0;
iChkBeforeToken = 0;
if(cOperation[ii] == ')'){
iChkCcount--;
if(iChkCcount < 0) return 0;
if(iChkC == 0) return 0;
if(iChkCcount == 0) iChkC = 0;
iChkBeforeToken = 1;
}
iCharCount++;
break;
case 'a': // 이곳부터 ------
case 'A': //
case 'b': //
case 'B': //
case 'c': //
case 'C': //
case 'd': //
case 'D': // ---- 여기까지 생락하면 모든 문자로 사칙연산 적용가능
case '(':
if(iChkBeforeToken == 1) return 0;
iChkBeforeToken = 1;
if(cOperation[ii] == '('){
iChkCcount++;
iChkC = 1;
iChkBeforeToken = 0;
}
iCharCount++;
break;
default:
return 0;
}
}
if(iChkCcount > 0) return 0; // 괄호가 하나라도 열려있는 경우
if((iCharCount % 2) == 0 || iCharCount < 2) return 0; // 토큰수가 작거나, 짝이 안맞을때
return 1;
}
void main(void)
{
char cOperation[100];
while(1){
fflush(stdin);
gets(cOperation);
if(cOperation[0] == NULL) break;
if(fChkToken(cOperation)) printf("Good !!\n");
else printf("Syntax Error !!\n");
}
}
입력예제 -
A+B+(a*b-c)+d
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_ // Korea Maritime Univ. Div. Automation & Information. /_ // Major. Computer Engineering. /_ // 9727052 Lee Gun-woo. ([email protected]) /_ // Parsing Source. /_ //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_ #include