Do while

Feb 22, 2016 at 4:33am
I have a simple question

So usually my do while menus will have a basic condition where if the user doesn't enter 'n' for NO, the menu will loop back

The problem I have is, if the user enters anything other than 'n', the menu will loop back, but I want the user to specifically enter only 'y' to reloop, and if the user enters anything else it will say "invalid choice"

Is the only option to do this is create a lenghty }while (... ) condition which deals with every single choice?
Feb 22, 2016 at 5:18am
Hi,

Instead of asking a yes/no question, provide a quit option in the menu, use a switch inside a bool controlled while loop. See here for an outline:

http://www.cplusplus.com/forum/general/83524/#msg448244


Should have a default: case to catch bad input, and one can use char instead of int in the switch.
Feb 22, 2016 at 5:44am
Ah yeah I understand, but if I strictly wanted to use a do while, how could I do it?
Feb 22, 2016 at 6:41am
If it's a yes/ no question, just use an if statement. Stick to a single char answer, use std::tolower, don't worry about checking validity of a no answer.

In a while loop, use the results of the yes/no question with bool variable in the condition of the while.

I am not a fan of do loops - they can be error prone. Just because they always execute once should not be a primary reason for choosing them over a while loop. All 3 loop constructs can be converted form 1 to another, maybe at the price of an extra variable.
Topic archived. No new replies allowed.