Hey guys. I was having some trouble with exercise 1-24 in the K&M. I asks for a program to check a C program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. I know my current program doesnt work perfectly, because it will count something like (()) as an error. However, I was confused about something else. I usually get a "state2r" value of 1 even if I don't input anything. Like I can input "abc" and it'll return a state2r value of 1. I was wondering if someone could take a look at it, because I am stumped. Thanks a lot.
Code:
#include <stdio.h>
#define MAXLINE 1000
#define IN 1 /* IN is inside parantheses/brackets/braces, OUT is out*/
#define OUT 0
int getfile(char line[], int maxline);
void check(char oldline[]);
int state1, state1r, state1l,state2, state2r, state2l, state3, state3r, state3l;
int getline(char s[], int lim)
{
int i, c;
for(i=0;i<lim-1 && (c=getchar())!='\n' && c!=EOF;i++)
s[i]=c;
if (c=='\n'){
s[i]='\n';
i++;
}
s[i]='\0';
return i;
}
void check(char oldline[]){
extern int state1, state1r, state1l,state2, state2r, state2l, state3, state3r, state3l;
/* state1 is parenthees. 2 is brackets. 3 is braces. #r is if there is unbalanced right side #l is if you have unbalanced left side */
int i;
state1= state1r= state2= state2r= state3= state3r=state1l=state2l=state3l = OUT;
for(i=0; oldline[i]!=EOF; i++){
if (oldline[i]=='(' && state1 == OUT)
state1 = IN;
else if (oldline[i]=='(' && state1 == IN)
state1l=IN;
if (oldline[i]==')' && state1 == IN)
state1=OUT;
else if (oldline[i]==')' && state1 == OUT)
state1r=IN;
if (oldline[i]=='[' && state2 == OUT)
state2 = IN;
else if (oldline[i]=='[' && state2 == IN)
state2l=IN;
if (oldline[i]==']' && state2 == IN)
state2=OUT;
else if (oldline[i]==']' && state2 == OUT)
state2r=IN;
if (oldline[i]=='{' && state3 == OUT)
state3 = IN;
else if (oldline[i]=='{' && state3 == IN)
state3l=IN;
if (oldline[i]=='}' && state3 == IN)
state3=OUT;
else if (oldline[i]=='}' && state3 == OUT)
state3r=IN;
}
}
main(){
int i;
char line[MAXLINE];
while ((i=getline(line, MAXLINE))>0){
check(line);
printf("If you see a one following the phrase then you have an unbalanced error of that type\n");
printf("Unclosed paranthese %d Extra left paratheses %d Extra right paranthese %d\n", state1, state1l, state1r);
printf("Unclosed bracket %d Extra left bracket %d Extra right bracket %d\n", state2, state2l, state2r);
printf("Unclosed brace %d Extra left brace %d Extra right brace %d\n", state3, state3l, state3r);
}
return 0;
}