Idalas
Idalas

Reputation: 83

Can't figure out why while loop is infinite

My code uses what I thought would be a simple while loop. It checks if the randCard already exists in the vector I have and, if it does, makes a new randCard.

I've added cout statements within the loop to try to find which processes it's running through and discovered it's only running through the while loop, none of the nested for loops. The problem is as follows:

    bool isSame = true;


    //Make sure they don't be the same cards

    while (isSame){
        cout << "While entered" << endl;
        for(int i = 0; i < notToUse.size(); i++){
            if(randCard == notToUse.at(i)){
                randCard = rand() % 24;

            }
            cout << "First for ran" << endl;
        }
        for (int i = 0; i < notToUse.size(); i++){
            if (randCard == notToUse.at(i)){
                cout << "Recheck loop" << endl;
                break;
            }
            else{
                cout << "Else ran" << endl;
                isSame = false;
            }
        }
    }

randCard is from a class of type Cards. The vector notToUse consists of cards indices that have already been used. The end cout statements end up looking like:

While entered
While entered
While entered
While entered
While entered

It seems like the for loops aren't even accessed. How can I fix this?

Upvotes: 0

Views: 63

Answers (1)

Idalas
Idalas

Reputation: 83

For anyone who might stumble upon this, the answer was resolved in the comments. The vector was of size 0, so the for loops didn't even run.

Upvotes: 2

Related Questions