Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat do while loop if switch statement reaches default

I have a do while loop asking for user input. Inside this do while loop I have a switch statement. How can I make it so that if the default value is met repeat the loop asking for the users gender again?

do
    {
        cout << "What is your weight?" << endl;
        cin >> weight;
        cout << "What is your height?" << endl;
        cin >> height;
        cout << "What is your age?" << endl;
        cin >> age;
        cout << "What is your gender?" << endl;
        cin >> gender;

        switch (gender)
        {
            case 'M':
            case 'm':
                cout << endl << Male(weight, height, age);
                break;
            case 'F':
            case 'f':
                cout << endl << Female(weight, height, age);
                break;
            default:
                cout << "What is your gender?";
        }

        cout << "Do you want to continue? (Y/N)" << endl;
        cin >> stopApp;

    } while(toupper(stopApp) == 'Y');
like image 516
Daniel Avatar asked Dec 21 '22 00:12

Daniel


2 Answers

One option is to set up a boolean value and if the default case is reached set it to true to repeat.

bool repeat;
do {
  repeat = false;
  //switch statement
  switch {
    default:
      repeat = true;
  }
while(repeat);

You could appropriately use repeat to know which question you would like to repeat as well.

like image 190
pippin1289 Avatar answered Jan 09 '23 19:01

pippin1289


A typical pattern for this kind of thing is to loop until the user enters valid input. IE

    do {
        cout << "What is your weight?" << endl;
        cin >> weight;
        cout << "What is your height?" << endl;
        cin >> height;
        cout << "What is your age?" << endl;
        cin >> age;
        cout << "What is your gender?" << endl;
        cin >> gender;
    } while (!validGender(gender));

    // process valid input

While this doesn't precisely answer your question, it is a good pattern for what you're trying to do.

like image 30
Doug T. Avatar answered Jan 09 '23 20:01

Doug T.