Valid Expression = single digit
AND
Valid Expression = ( Valid Expression + Valid Expression )
Which means that the boolean function that I’m trying to create will only accept as valid, expressions of the following type:
5
(5+3)
(6+(3+2))
((7+1)+(5+1))
............... etc.
I want my function’s parameters to stay as they are (istringstream& is) and I want to use a get(ch) in my function.
I also want to do it recursively. However, I’m doing something wrong and it only validates expressions of type : single digit
Where’s the problem in my recursion? And I know it’s not even a proper recursion, I’m sure a proper recursion could do the job even in fewer lines and with no nested ifs..
Thank you for any helpful suggestions!
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
bool isvalid(istringstream& is)
{
char ch;
is.get(ch);
if(ch-'0'>=0 || ch-'0'<=9) return true;
if(ch=='(' && isvalid(is))
{
is.get(ch);
if(ch=='+' && isvalid(is))
{
is.get(ch);
if(ch==')') return true;
}
}
return false;
}
bool empty(istringstream& is)
{
char ch;
is.get(ch);
return is.fail();
}
int main()
{
string s;
while(getline(cin,s))
{
istringstream is(s);
cout<<(isvalid(is) && empty(is) ? "Expression OK" : "Not OK")<<endl;
}
}
This needs to be an && expression, doesn’t it?