'val2' was not declared in this scope

i am getting this 'val2' was not declared in this scope error when i think it is declared.

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

//part of the code
  int evaluatePostfix(string& exp)
{
    stack* Stack=createStack(exp.length());
    for(int i=0;i<exp.length();i++)
    {
        if(isDigit(exp[i]))
        {
            push(Stack,exp[i]);
        }
        else//by default an operator\
        {
            int val2=pop(Stack);
            int val1=pop(Stack);
            switch(exp[i])
            {
                case '+':push(Stack,val1 + val2);break;
                case '-':push(Stack, val1-val2);break;
                case '*':push(Stack, val1*val2);break;
                case '/':push(Stack, val1/val2);break;

            }
        }
    }
    return Stack->array[0];
    }

int main()
{
    string exp="231*+9-";
    cout<<evaluatePostfix(exp);

}
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/192442/
Line 12: remove the \ at the end of the line.
@kemort yes, that's my post. but what do you mean by that?
@coder777 honestly, initially i just thought to directly reply without even testing it. "oh it wouldn't work, it's just a comment.He/she(idk why but i assume 'he' though, but i swear to god, i am not a sexist) must've made a mistake." but decided to do it anyway. well, I haven't been surprised like this in while. whaaat!?? how does it work? '\' is a comment after all.
Last edited on
The back slash will extend the single line comment to the next line. In this case line 13 will also been commented and hence only line 14 belongs to the else.

He.
It looks like the real question is, "how to convert the code from this page to use std::string instead of char *"

http://geeksquiz.com/stack-set-4-evaluation-postfix-expression/


Notice this difference. From geeksquiz page:
1
2
        if (isdigit(exp[i]))
            push(stack, exp[i] - '0');

From OP code:
1
2
3
4
        if(isDigit(exp[i]))
        {
            push(Stack,exp[i]);
        }


See the difference - the - '0' has been omitted. That might be something to consider when you later find out the code doesn't work.
Last edited on
@coder777 thanks!

Crushed it!

@Chervil actually, my "push" function took care of that.
my push function
1
2
3
4
void push(stack* Stack, char ch)
{
    Stack->array[++Stack->top]=ch-'0';//works?? check
}


geeksquiz page:
1
2
3
4
void push(struct Stack* stack, char op)
{
    stack->array[++stack->top] = op;
}

but i later did realize that, geeksquiz's one was much cleaner.
Topic archived. No new replies allowed.