I am writing a program to read a bunch of text and perform boolean operations on it and outputting the result. e.g "T F && T || !" should output false.I have designed my program ,written a parser to get the chars and a method to perform boolean operations.My only problem is that evaluation of expressions is not working.
Code:
struct stack{
char *characters;
int top;
};
/*This function initialises and returns a stack adt
the stack size if allocated a default value of 4 because i know that there can
* only be at most 2 values on the stack at any time
*/
struct stack * newStack(){
struct stack * p= malloc(sizeof(struct stack));
if(!p){
fprintf(stderr,"out of memory\n");
}
p->top=0;
p->characters=malloc(sizeof(char)*6);
return p;
}
/* a void method which is used to push
* char onto the stack
*/
void push(char *c, struct stack *p){
p->characters[p->top]=*c;
p->top++;
}
/*
a double method called pop used to
* pop char of the stack
*/
char * pop(struct stack *p){
char * c;
p->top = p->top - 1;
c=p->characters[p->top];//assing the char the value of the index
p->characters[p->top]=' '; //clean up the index
return c;
}
/*
takes 4 parameters
* a=top of stack -1
* b=top of stack -2
* result=where the result woud be stored
* operation= boolean operation to be performed
*/
void performoperation(char *a,char *b,char * result,char *operation){
const char *t="T";
const char * and="&";
const char *or="|";
const char *not="!";
int i,j;
// if (strcmp(a,t)==0)
if (*a==*t)
i=1;
else
i=0;
if (*b==*t)
j=1;
else
j=0;
int jy=0;
if(strcmp(operation,and)==0){
jy=i && j;
}
else
if(strcmp(operation,or)==0)
jy=i || j;
else
if(strcmp(operation,not)==0)
{
jy= (!i);
}
if(jy==1)
*result='T';
else
*result='F';
}
/*
been stuck in this method for a while
*/
void evaluateExpression(char *expressions,struct stack * stack){
char *a;
char *b;
char *res;
while(*expressions!='\0'){
if(*expressions=='T' || *expressions=='F') {//if its a t or f
push(expressions, stack);
}
else{
a=pop(stack);
b=pop(stack);
performoperation(a,b,res,expressions);
push(res,stack);
}
expressions++;
}
}
void parseexpressionfromcommandline(char * unparsedexpression,char *parsedexpression){
if(unparsedexpression==NULL )
printf("does not point to any address");
else {
char value; //this would hold my value
int pos=0;
while(*unparsedexpression!='\0'){
while(!isspace(*unparsedexpression)&& (*unparsedexpression)!='\0'){
value=(*unparsedexpression++);
}//inneer while loop
unparsedexpression++;
parsedexpression[pos++]=value;
}//outer while loop
parsedexpression[pos]='\0';
}//outer while
}
int main(int argc, char** argv) {
char result[13];
char *p="T F && F || !\0";
char *v;
char * u;
//char * q='u';
struct stack *stack;
v=result;
stack= newStack();
parseexpressionfromcommandline(p,v);
printf("%s \n",v);
printf("%u",strlen( v));
evaluateExpression(v,stack);
return (EXIT_SUCCESS);
}