I need help in writing a program that will evaluate an expression from a file and output if the expression is a valid C++ expression or not.
EXAMPLE This is read from input file:
Input:
a
ab
(a+b)
(a)
This is ouput to screen after each read and test till end of file.
Output:
a
** Is a valid expression **
ab
** Is N O T a valid expression **
(a+b)
** Is a valid expression **
(a)
** Is N O T a valid expression **
As far as I know the rule for a valid expression in c++ is that all the operators must be paranthized. This is my program below but it doesn't work properly can someone point out mistakes?
------------------------------------------------------------------------------------
#include <fstream.h>
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
#define in_file "input.dat"
void FindAnExpression(int[]);
ifstream ins;
ofstream outs;
char line[20];
int main()
{
int test = 0;
ins.open(in_file);
if(ins.fail())
{
cout <<"*** ERROR: Cannot open "<< in_file
<<"for input." << endl;
exit(1);
}
do
{
ins.getline(line,20);
cout << line;
test= FindAnExpression(line);
if (test==1)
cout << "This is a valid Expression.";
else
cout << "This is NOT a valid Expression.";
}while(!ins.eof())
return 0;
}
FindAnExpression(int[]);
{
int index = 0;
if isalpha(line[index])
{
index++
if isalpha(line[index])
return 1;
else if (line[index]='(')
{
FindAnExpression
if ((line[index]='+') || (line[index]='-') || (line[index]='*') || (line[index]='/'))
FindAnExpression
if (line[index]=')'
return 1;
}
return 0;
}
}