while(cin)

Hello,

I have a question regarding a loop I don't fully understand.

Here's the problem: We are writing a calculator, and we wan't him to not only understand simple expressions like 5+5 but also 5+7-1.

Here's the part of the code I have problems with:


1
2
3
4
5
6
7
    cin >> lval; //read left most number
    if (!cin) error("No first operand");

    while (cin >> op) //Repeatedly read operand and right value
    {
        cin >> rval;
        if (!cin) error("No second operand");


First we read in the left value, fine.
Then the loop starts and we read in op, the operator, and in the loop we read in the right value.

What I don't understand is how the loop ever returns to the "cin >> op" part,
if we enter 5 (lval), + (op), and 5 (rval), how will the program understand another operator (like -) will be read into the "op" variable instead of rval?

Thanks in advance.
When the closing brace of the while loop is reached, execution returns to the top of the loop. Before entering the body of the loop, the condition is tested. That means executing the cin >> op statement. If this is successful (a value of op was read from cin) then the body of the loop will be executed, and a value of rval will be read from cin.
I guess that makes sense. Thanks a lot!
Topic archived. No new replies allowed.