After several hours of brainstorming, it would seem i cannot solve this on my own, so i am humbly asking the experts here for some expert help (and if possible, some code snippets)
My problem is this:
1) User is asked to input a mathematical expression in INFIX form (the normal way).
2) My program then checks the expression for any syntax errors. (im stuck here for now).
3) It then converts it to postfix (or Reverse Polish Notation), then evaluates it.
examples of erroneous expressions are:
5 ( 5 + 5) 5 (no operation between parenthesis)
5 5 + 5 (5 5 is treated as two different numbers due to white space between)
5 + + 5 (double addition operation without operands)
+ 5 + 5 + (insufficient operands)
) 5 + 5 (invalid parenthesis placement)
( ( 5 + 5) (parenthesis mismatch)
...... other errors which you guys know but i havent figured out yet.
so far, i think i've solved the mismatched parenthesis problem. the rest seems too difficult for me.
i know how to do 3), but 2) seems to elude my wits. can anyone help me? this is what i've accomplished so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
typedef struct stackA {
char *token;
stackA *next;
} stack;
typedef *stack stack_ptr;
int errorCheck(char *input);
char *output(char *input);
int evaluate(char *output);
char *pop(stack_ptr S);
void push(char *c, stack_ptr S);
int isOperator(char c);
int main(void) {
char input[MAX], *output, try_again;
int choice, error, answer;
do {
clrscr();
error=0;
puts("Enter the infix notation:");
fgets(input,sizeof(input),stdin); /* to prevent buffer overflow*/
error=errorCheck(input);
if(error != 0)
puts("You have enterred an erroneous equation!");
else {
output=convert(input);
printf("\nConverted to postfix: %s",output);
answer=evaluate(output);
printf("\nThe answer to the equation %s is: %d",input,answer);
}
puts("\nDo you wish to try again? \(type \"N\" to quit, any other to repeat\)");
try_again=getchar();\
} while(!(try_again == 'N' || try_again == 'n'));
getch();
}
int errorCheck(char *input) {
int i, len, found_error=0,Lparenthesis=0,Rparenthesis=0,digit=0,operator_start=0, operator_end=0;
len=strlen(input);
for(i=0;i<len && found_error==0;i++) {
while(isspace(input[i]))
i++;
if(input[i] == '(')
Lparenthesis++;
else if(input[i] == ')') {
if(Lparenthesis == 0)
found_error=1;
else Rparenthesis++;
}
if(isdigit(input[i])) {
digit=1;
while(isdigit(input[i]))
i++;
while(isspace(input[i]))
i++;
if(isdigit(input[i]) || input[i] == '(' || input[i] == ')')
found_error=1;
else digit=0;
}
}
}
note) the program isnt finished yet, but if I separate the errorCheck function and convert it into a program, it compiles, but the expression (5 + 5) is reported as having errors. i tried to trace the sequence of the program but to no avail, i just couldnt see the problem.
thanks in advance!