While Loop error

This is exact copy code from the book but does not run perfectly. why?

He added while loop so expression such as 3+3+3+3+...+n can occur rather than a+b;

The only way this loop ends is if I type some characters then the loop stops and produces the result!


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
  #include<iostream>

using namespace std;

int main()
{
    cout<<"Enter expression:  ";
    int lval=0;
    int rval;
    char op;
      
    
    cin>>lval;
    
    
    if(!cin) cerr<<"no first operand";
    while(cin>>op){
        cin>>rval;
        if(!cin) cerr<<("no second operand");
        switch(op){
                case '+':
                    lval+=rval;
                    break;
                case '-':
                    lval-=rval;
                    break;
                case '*':
                    lval*=rval;
                    break;
                case '/':
                    lval/=rval;
                    break;
            default:
                cout<<"Result : " <<lval<<endl;
                
                    
        }
        
        
    }
    cerr<<"Bad Expression";
      
        
}





Book is Programming Principle by Bjarne Stroustrup
Last edited on
Please explain the "does not run perfectly."
@keskiverto So, If I type 5+5+5 then it does nothing!. Shouldn't it just produce an output once pressed Enter. The only way this loop ends is if I type some characters. After that, it prints out the result!
Last edited on
Yes.

Line 13 reads the first '5'.
Line 17 reads the first '+'.
Line 18 reads the second '5'.
The switch statement executes line 22 and the loop starts new iteration from line 17.
Line 17 reads the second '+'.
Line 18 reads the third '5'.
The switch statement executes line 22 and the loop starts new iteration from line 17.

In order to see a result you have to reach the default (line 33) and that requires that the character read on line 17 is none of +-*/.

In order to quite the loop, either line 17 read has to fail (EOF would do it)
or line 18 read has to fail (if there is no integer in the stream).

Quitting the loop always writes "Bad Expression". Not intuitive.


Exact copy from a book? Have any erratas been published after print of that edition?
@keskiverto Thanx a lot for explaining. I copied exactly the same. This is a chapter for building calculator on page 178 and he quickly dives into the result rather than explaining the code. I thought since he says there will be a result, i figured the result should come out with no problem. He is doing like Version 1.0 and 2.0 etc, but this error was not one of the error that was discussed and fixed later on in the book! Anyhow, Thank You!
Topic archived. No new replies allowed.