I'm trying to better understand this code from the book "Programming: Principles and Practice Using C++ (2nd Edition)" by Bjarne Stroustrup.
I did try searching, but for one reason or another, the answers I found didn't really answer my questions.
I just started a few days ago, so I apologize for any mistakes.
This code is nearly identical to the example in the book.
It uses his "std_lib_facilities.h"
The error("") call just throws a runtime error as far as I know.
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
|
cout << "Expression: ";
int lval = 0;
int rval;
char op;
cin >> lval;
if (!cin) error("no first operand");
while (cin >> op) {
cin >> rval;
if (!cin) error("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 << '\n';
keep_window_open();
return 0;
}
}
error("bad expression. \n");
|
My problem is that the book implies it will show the result if you just enter, for example, 1+2+3. But when I do this, nothing happens.
The only way I can get the answer to show is by one of two ways:
-enter equation followed by a random character and a random number. (ex: 1+1d7)
-enter equation, press enter, enter another random equation.
-(There's more ways but they're just variations of the above).
Both of these seem to produce the correct result, regardless of what's entered after the equation. Anything else and the program closes, or I get one of the errors. I'm not entire sure why these work, and would also like an explanation, if possible.
Looking again, does the code above mean that anytime an operator is detected, a number must follow? I thought of making it only ask for input if the last character wasn't a '=', but I would like to get the original code to work as the book implies first, if that's possible.