[SOLVED] I don't understand how cin.ignore() works. When I run this piece of code, my program breaks down

Issue

There is an array of classes. I want to input an amount of players and then by using a for-loop, input player’s names. The problem is that I don’t understand how to avoid the program crashing, using cin.ignore().

void main() {
    int numberOfPlayers;
    cout << "Input amount of players:";
    getline(cin, numberOfPlayers);
    Player** arrOfPlayers = new Player*[numberOfPlayers];
    string newName;

    for (int i = 0; i < numberOfPlayers; i++) {
        cout << "\nInput player " << i + 1 << " nickname: ";
        getline(cin, newName);
        arrOfPlayers[i]->setName(newName);
    }
}

Solution

You have not allocated the individual players

This

Player** arrOfPlayers = new Player*[numberOfPlayers];

only allocates an array of pointers to players

You also need to create those players

for (int i = 0; i < numberOfPlayers; ++i)
   arrOfPlayers[i] = new Player;

Answered By – AndersK

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *