lundi 5 février 2018

Issue storing words in a string pointer

I am trying to dynamically allocate memory for an array that will hold a set of names. The memory has a max of five elements in the array and the user will manually type in a first, middle and last name on one line. I am trying to print out the elements of the array to make sure they are getting stored properly but for whatever reason the first element is blank. I am very lost on this. I have been trying to solve this issue but not is working.

playerAmount is a separate variable in another function where the user will enter how many players they want (range 2 - 5) and depending on that int playerAmount will ask the user's names depending on what int they put.

I am having the issue in the getName function

void amountOfPlayers(int &playerAmount) {

    cout << "Enter the amount of players: ";

    cin >> playerAmount;

    while (cin.fail()) { // Input Validation - if user enter's letters

        cout << "ERROR: must be a number, try again: ";

        cin.clear();

        cin.ignore(1000, '\n');

        cin >> playerAmount;
    }

    while ((playerAmount < 2) or
           (playerAmount >
            5)) { // Input Validation - if user enters numbers out of range

        cout << "ERROR: must be a number between 2-5, try again: ";

        cin.clear();

        cin.ignore(1000, '\n');

        cin >> playerAmount;
    }
}

void getName(int &playerAmount, string *&playerNames) {

    int i = 0;

    for (; i < playerAmount; i++) {

        cout << "Player " << i + 1 << " enter your full name: ";

        getline(cin, playerNames[i]);

        cin.clear();

        cin.ignore(1000, '\n');

        cout << playerNames[0];
    }
}

int main() {

    int playerAmount;

    string *playerNames = NULL;

    playerNames = new string[playAmount];

    amountOfPlayers(playerAmount);

    getName(playerAmount, playerNames);
}

Aucun commentaire:

Enregistrer un commentaire