Question

When the program enters the second loop it becomes infinite even though I'm setting the value for the second loop false. Where is the problem occurring? The first while loop I never encounter any problems exiting, but the second one... I just cannot see where or why.

int RareData::assignRareType()
{

    int switchType;
    std::cin >> switchType;
    bool valid = true;
    bool valid2 = true;

    while (valid)
    {
        switch (switchType)
        {

        case 0:
            std::cout << "1 - Character Change\n2 - Account Change\n3 - Both\n";
            int switchData;
            std::cin >> switchData;
            valid2 = true;

            while (valid2)
            {
                switch (switchData)
                {
                case 1:
                    valid2 = false;
                    std::cin.clear();
                    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    assignCharacter();
                    break;
                case 2:
                    valid2 = false;
                    std::cin.clear();
                        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    assignAccount();
                    break;
                case 3:
                    valid2 = false;
                    std::cin.clear();
                    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    assignAccount();
                    assignCharacter();
                    break;
                default:
                    std::cout << "Options only range from 1-3\n1 - Character Change\n2 - Account Change\n3 - Both\n";
                    std::cin.clear();
                    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    std::cin >> switchData;
                }
            }
            break;
        default:

            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cin >> switchType;
        }
    }
    return 0;
}
Was it helpful?

Solution

You set valid2 to false, however valid is still true. So your first while loop runs over and over again. The order of execution is as follows:

while(valid) == true
    case 0:
           get switchdata, set valid2 = true
                second while loop
                 break
Repeat because valid is always true, switchtype never changes.

OTHER TIPS

The variable valid is initialised as true and never changed, so in fact it is the first while loop that never terminates, not the second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top