repeat do while loop if switch statement reaches default

Mr. 1.0 picture Mr. 1.0 · Sep 18, 2013 · Viewed 26.7k times · Source

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');

Answer

pippin1289 picture pippin1289 · Sep 18, 2013

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.