Evaluating arithmetic expressions using recursive descent parser

I have the following code to calculate arithmetic expressions :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
using namespace std;

using namespace std;

const char * expressionToParse = "6.5-2.5*10/5+2*5";

char peek()
{
    return *expressionToParse;
}

char get()
{
    return *expressionToParse++;
}

double expression();

double number()
{
    double result = get() - '0';
    while (peek() >= '0' && peek() <= '9')
    {
        result = 10*result + get() - '0';
    }
    return result;
}

double factor()
{
    if (peek() >= '0' && peek() <= '9')
        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;
}


The problem is that it does not work properly with decimal numbers
for example it evaluates 6-2*10/5+2*5 = 12 which is correct but for 6.5-2.5*10/5+2*5 it returns 6 instead of 11.5 .
can someone please help me to fix this issue ?
Last edited on
number doesn't handle decimal points (and if it did factor doesn't.)
Last edited on
is there anyway to modify it to handle decimals ? I am not really sure what to do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <sstream>
#include <iostream>
using namespace std;

const char * expressionToParse = "6.5-2.5*10/5+2*5";

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();
    // rest of the code doesn't require change... 
Topic archived. No new replies allowed.