Home > OS >  Loop control inside void function keeps looping
Loop control inside void function keeps looping

Time:12-01


void getDay() {
    bool repeat;
    do
    {
        cout << "Enter the day code (first 2 letters): ";
        cin >> weekDay1;
        cin >> weekDay2;
        weekDay1 = toupper(weekDay1);
        weekDay2 = toupper(weekDay2);
            
        switch (weekDay1)
            {
                case 'M':
                    break;
                case 'T':
                    break;
                case 'W':
                    break;
                case 'F':
                    break;
                case 'S':
                    break;
                default:
                    cout << "Invalid input. Please try again.\n";
                    repeat = true;
                break;
            }
            
        switch (weekDay2) 
            {
                case 'O':
                    break;
                case 'U':
                    break;
                case 'E':
                    break;
                case 'H':
                    break;
                case 'R':
                    break;
                case 'A':
                    break;
                default:
                    cout << "Invalid input. Please try again.\n";
                    repeat = true;
                break;
            }
    
    }while (repeat == true);
        
        return;
}

I need this function to run once, and loop if the input is not one of the accepted characters. I'm trying to prevent any bad input, but it loops infinitely if the input entered on the initial run is not accepted. It works fine if the input is good on the first run, but I keep getting run-time errors for not initializing bools and I need some help adjusting this control.

CodePudding user response:

The condition in the while loop is always true because you never set it to false in its body. You can do something like this:

void getDay() {
  // Initializing while declaring is a good practice.
  bool repeat = false;

  do {
    .
    .
    repeat = false;
    .
    switch(...) {
      ...
    }
  } while (repeat);
}

Now, repeat = true is only called if one of the switch statements invokes default.

  • Related