So I'm working on a project for a class in which we have to create a parser for a made up grammar. The input is read from a file. When I use input that is in the grammar, the program works. For certain input not in the grammar such as 9=b+a (which is not in the grammar) the program says it is not in the grammar. However, when I test other input that is not in the grammar such as b=g**h (basically whenever I use two operators (+ - / *) in a row, the program crashes with I believe a segmentation fault. Any ideas why this is happening? Thanks in advance for your help. Here is my code with the grammar at the top commented out.
/*
A -> I = E
E -> T + E | T - E | T
T -> P * T | P / T | P
P -> I | L | (E)
I -> a | b | ... | y | z
L -> 0 | 1 | ... | 8 | 9
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool literal(char *);
bool integer(char *);
bool primary(char *);
bool term(char *);
bool expr(char *);
bool assign(char *);
int main ()
{
ifstream inFile;
inFile.open("experiment.txt");
string line;
inFile >> line;
char *c;
c = &line[0];
cout << "String read from file: " << line << endl;
if (assign(c))
cout << "The string: '" << line << "' is in the language" << endl;
else
cout << "The string: '" << line << "' is not in the language" << endl;
system("Pause");
return 0;
}
bool assign (char *c)
{
if (integer(c))
{
++c;
if (*c == '=')
{
++c;
if (expr(c))
{
++c;
return true;
}
}
}
else
return false;
}
bool literal(char *c)
{
if (*c == 0 || *c == 1 || *c == 2 || *c == 3 || *c == 4 || *c == 5 || *c == 6 || *c == 7 || *c == 8 || *c == 9)
{
return true;
}
return false;
}
bool integer (char *c)
{
cout << "in integer" << endl;
if (*c == 'a' || *c == 'b' || *c == 'c' || *c == 'd' || *c == 'e' || *c == 'f' || *c == 'g' || *c == 'h' || *c == 'i' || *c == 'j' || *c == 'k' || *c == 'l' || *c == 'm' || *c == 'n' || *c == 'o' || *c == 'p' || *c == 'q' || *c == 'r' || *c == 's' || *c == 't' || *c == 'u' || *c == 'v' || *c == 'w' || *c == 'x' || *c == 'y' || *c == 'z')
{
return true;
}
else
return false;
}
bool primary (char *c)
{
if(integer(c))
return true;
else if (literal(c))
return true;
else if (*c == '(')
++c;
if (expr(c))
{
++c;
if (*c == ')')
{
++c;
return true;
}
else
return false;
}
else
return false;
}
bool term (char *c)
{
if (primary(c))
{
++c;
if (*c == '*' || *c == '/')
{
++c;
if (term(c))
{
return true;
}
else
return false;
}
return true;
}
else
return false;
}
bool expr (char *c)
{
if (term(c))
{
++c;
if (*c == '+' || *c == '-')
{
++c;
if (expr(c))
{
return true;
}
}
return true;
}
else
return false;
}