Evaluating arithmetic expressions using recursive descent parser

Apr 6, 2018 at 7:00am
#include <sstream>
#include <iostream>

using namespace std;

using namespace std;

//const char * expressionToParse = "6.5-2.5*10/5+2*5";
const char * expressionToParse = "-5+2";
istringstream parse(expressionToParse) ;

char peek()
{
return static_cast<char>(parse.peek()) ;
}

char get()
{
return static_cast<char>(parse.get()) ;
}

double expression();

double number()
{
double result ;
parse >> result ;
return result;
}

double factor()
{
if ((peek() >= '0' && peek() <= '9') || peek() == '.')
return number();
else if (peek() == '(')
{
get(); // '('
double result = expression();
get(); // ')'
return result;
}
else if (peek() == '-')
{
get();
return -expression();
}
return 0; // error
}

double term()
{
double result = factor();
while (peek() == '*' || peek() == '/')
if (get() == '*')
result *= factor();
else
result /= factor();
return result;
}

double expression()
{
double result = term();
while (peek() == '+' || peek() == '-')
if (get() == '+')
result += term();
else
result -= term();
return result;
}

int main(double argc, char* argv[])
{

double result = expression();
cout << result << endl;
return 0;
}


// This is working fine for all inputs but when we enter input as -3+2 answer is -5 can someone help
Apr 6, 2018 at 11:57am
The problem is in factor():
1
2
3
4
5
else if (peek() == '-')
{
get();
return -expression();
}
You need to return a negative number not an expression.
Apr 6, 2018 at 12:40pm
You need to return a negative number not an expression.


But that won't handle a case like -(22+4). I think the code needs to return a negative factor, not a negative number.
Apr 6, 2018 at 12:43pm
Hi @coder777 and dhayden.... if you could give the code snippet as in where and what to change . I need it as an urgent code assigment. Please help
Apr 6, 2018 at 8:00pm
We have given enough information for you to figure it out. Sorry, but the goal of this website is to help you become a better programmer, not to do your work for you.
Apr 7, 2018 at 1:25pm
dhayden wrote:
But that won't handle a case like -(22+4).
I will when using factor() instead of expression().
Apr 7, 2018 at 8:33pm
coder777 wrote:
It will when using factor() instead of expression().

But that isn't the advice you gave:
coder777 wrote:
You need to return a negative number not an expression
This says that OP should return -number(); instead of return -expression();

In response, I said:
the code needs to return a negative factor.
We seem to agree that return -factor(); is the right code.
Apr 9, 2018 at 8:01am
dhayden wrote:
But that isn't the advice you gave:
I wasn't refering to the function number(). Actually I did not see that such a function exists. It was not intended as the solution.

In order to avoid such a confusion functions should have a verb like calc_number() or so.
Topic archived. No new replies allowed.