问题在字符串指针中存储单词
Issue storing words in a string pointer
我正在尝试动态分配一个将包含一组名称的数组的内存。内存中的数组中有五个元素,用户将在一行中手动输入一个,中间和姓氏。我试图打印出数组的元素,以确保它们得到正确的存储,但是无论出于何种原因,第一个元素都是空白的。我对此非常迷失。我一直在尝试解决这个问题,但行不通。
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
。
使用时您还需要正确拼写。
相关文章:
- 如何将行的第一个单词作为一个变量,将行的其余部分作为另一个变量进行归档/存储
- 在字符数组中存储和恢复一组单词
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 无法在C 中的双重链接列表中存储每个单词
- 如何将整个单词存储在单个阵列插槽中
- 需要将单词的文本文件存储到C 中的字符阵列中
- 问题在字符串指针中存储单词
- 如何轻松快速地存储大型单词数据库?
- DAWG可以用于存储与单词相关的信息吗?
- 将文件中的各个单词存储到字符串类数组(C++)中的元素中
- 用于存储在文件中的单词的固定大小
- 读取单词并将它们存储到数组中
- 书籍索引,如何查看每个单词并根据其第一个字母进行存储
- 将地址和布尔值存储在一个单词中,以实现无锁双链表
- 从文件中提取行.txt然后将单词存储到单独的数组中 |C++
- C++ 将存储为 char* 的 4 个字符的单词转换为 int,反之亦然
- 将用户输入的前两个单词分隔一个空格,然后存储剩余短语(C++)
- 取一个包含任意数量单词的字符串,并将这些单词存储在不同的字符串变量中
- 从文件中逐字符读取单词列表,并将其存储在数组中
- 是否可以将用户输入的单词存储为字符数组?