Hi, I need some help with this program. This problem is from "Programming: Principles and Practice using C++" by Bjarne Stroustrup. The problem is, when there are no cases left, the default case doesn't run, the switch just exits. Is it because there are no operators left? How can I fix this?
When there are no more operators, I want the default case to be used. From what I'm understanding, there needs to be some character present for this to happen instead of nothing. How can I get the default case to run when there are no operators left?
By "no operators left", do you mean that the user presses ENTER at the prompt without entering a character?
If so, then that causes the while loop to exit, which means that no code in your switch-case statement will execute. Anything that you want to happen when the loop exits, you'll have to put after the loop.
In practice, one could exit the loop while (cin >> op) by signalling 'end of input' by pressing ctrl-Z or ctrl-D. Normally however, pressing enter results in the prompt continuing to wait for more input. Any 'invalid' character will do - but then the next prompt cin >> rval; will be reached. Here, it is ok to enter anything at all - even if that cin statement fails, it doesn't matter when the default case is executed.
Thanks for the help. I realized that instead of printing the result from inside the default case, I just moved it to outside the while (cin >> op) loop. Here is the modified code, which works much better: