问题在字符串指针中存储单词

Issue storing words in a string pointer

本文关键字:存储 单词 指针 字符串 问题      更新时间:2023-10-16

我正在尝试动态分配一个将包含一组名称的数组的内存。内存中的数组中有五个元素,用户将在一行中手动输入一个,中间和姓氏。我试图打印出数组的元素,以确保它们得到正确的存储,但是无论出于何种原因,第一个元素都是空白的。我对此非常迷失。我一直在尝试解决这个问题,但行不通。

PlayerAmount是另一个功能中的一个单独的变量,用户将输入他们想要多少播放器(范围2-5(,并取决于INT PlayerAmount,会根据他们放置的int询问用户的名称。

我在getName函数中遇到问题

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);
}

问题似乎是输入缓冲区。我在阅读playeramount后使用cin.ignore((和cin.clear((函数:

cin >> playerAmount;
cin.ignore(1000, 'n');
cin.clear(); 

我对其进行了测试,并且似乎可以工作。

另外,正如SID S在其他答案中提到的,应在分配字符串之前初始化playeramount:

 amountOfPlayers(playerAmount);  //initialize playerAmount
 playerNames = new string[playerAmount]; //allocate memory for that size

您需要在使用它之前初始化playerAmount

使用时您还需要正确拼写。