wrong answer with calculator

Hi guys I am making a simple token calculator

and I am getting unexpected results for some reason when I type 2 + 2 q the answer will be 2 yet I add the rval to val but it only seems to hold the value of the last rval instead of adding it to val


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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
  #include <iostream>
#include <vector>

using namespace std;

class Token{

   public:
       char type;
       double value;

       Token(char type):
       type(type),value(0){}
       Token(char type,int value):
       type(type),value(value){}
};

void populate(vector<Token> &tokens){

    char val;
    cout << "enter expression" << endl;

    while(true){

    cin >> val;
    switch(val){

case 'q':{
    Token t(val);
    tokens.push_back(val);
    return;
}
case'+':{
    Token t(val);
    tokens.push_back(t);
    break;
}
case '1': case '2': case '3': case '4': case '5':{

    cin.putback(val);
    int use;
    cin >> use;
    Token t('8',use);
    tokens.push_back(t);
    break;

}
default : cout << "something may have gone wrong" << endl;
    }
}
}

int main()
{
     vector<Token> tokens;
     populate(tokens);

     for(int i = 0; i < tokens.size(); i++){

           if(tokens.at(i).type == '8'){

            cout << tokens.at(i).value << endl;
           }
           else{

            cout << tokens.at(i).type << endl;
           }
     }
     int val = 0;
     int i = 0;
     int rval = 0;
     while(true){

        Token t = tokens[i];

        switch(t.type){

case 'q':{

    cout << "answer " << val << endl;
    return 1;
}
case'+':{

    val += rval;
    i++;
    break;
}
case '8':{

    rval = t.value;
    i++;
    break;

}
default : cout << "something may have gone wrong" << endl;
    }
}
}
you type 2+2q
it does some things and ends up in the + part of the switch statement.
at this point, cout of val is zero, then you add 2 to it, then it hits q, and it exits, answer = 2.

so the root problem is that val = 0 when it should be assigned 2 somewhere, somehow.

to see this, add print statements before and after the val += statement.
Topic archived. No new replies allowed.