C++ 如何向数组中添加或删除用户输入?C++;
假设我获得用户输入。如果他们键入的内容不在数组中(如何检查数组?),请将其添加到数组中。 反之亦然,在给定用户输入的情况下,如何从数组中删除某些内容 例如:C++ 如何向数组中添加或删除用户输入?C++;,c++,arrays,C++,Arrays,假设我获得用户输入。如果他们键入的内容不在数组中(如何检查数组?),请将其添加到数组中。 反之亦然,在给定用户输入的情况下,如何从数组中删除某些内容 例如: string teams[] = {"St. Louis,","Dallas","Chicago,","Atlanta,"}; cout <<"What is the name of the city you want to add?" << endl; cin >> add_city; c
string teams[] = {"St. Louis,","Dallas","Chicago,","Atlanta,"};
cout <<"What is the name of the city you want to add?" << endl;
cin >> add_city;
cout <<"What is the name of the city you want to remove?" << endl;
cin >> remove_city;
stringteams[]={“圣路易斯”、“达拉斯”、“芝加哥”、“亚特兰大”};
cout要向数组添加信息,可以执行以下操作:
for (int i = 0; i < 10; i++)
{
std::cout << "Please enter the city's name: " << std::endl;
std::getline(cin, myArray[i]);
}
for(int i=0;i<10;i++)
{
std::cout内置数组的大小是不可变的:既不能删除元素,也不能添加任何元素。我建议使用std::vector
,相反:向std::vector
中添加元素,例如,可以使用push_back()
来完成。要删除元素,可以使用std::find())
,然后使用擦除()
将其删除
如果需要使用内置数组(尽管我看不出有什么好的理由),可以使用new std::string[size]
在堆上分配一个数组,并保持其大小,在适当的时候使用delete[]适当地释放内存数组;
使用数组,可以用字符*处理空数组单元格,如“empty”。要查找项目,请在数组中搜索,然后查找以“替换”或添加它
const char * Empty = "EMPTY";
cout << "Please enter a city you want to add:"
cin >> city;
for(int i = 0; i < Arr_Size; i++) //variable to represent size of array
{
if(Arr[i] == Empty) //check for any empty cells you want to add
{
//replace cell
}
else if(i == Arr_Size-1) //if on last loop
cout << "Could not find empty cell, sorry!";
}
const char*Empty=“Empty”;
城市;
for(int i=0;i cout+1。如果你想让事情在任何地方都是动态的,向量绝对是一种方法。你的团队中有一些额外的逗号
不会使数组变长;它使数组的长度取决于初始值设定项列表的长度,在本例中为4。从那时起,它与固定长度数组相同。std::vector
是您真正想要的。注释是故意的。我正在学习数组,并被告知只使用数组…我说的是逗号而不是注释。例如.“圣路易斯”
应该是“圣路易斯”
。我很困惑。数组是固定长度的。因此“将其添加到数组中”没有意义;无论你选择的长度是多少,在某一点上你都可能用完插槽。现在,如果你应该在堆上使用数组,那么你需要Dietmar答案的第二段。为什么不使用长度为零的字符串,即“”
?编辑帖子以显示我的意图,打印时它跳过了“空”单元格。在我看来,您似乎已将Arr
声明为std::vector Arr;
…您应该显示它。string Arr[]
不起作用,因为内置数组没有size
方法。我使用Arr表示数组,并调整一个函数的大小以显示数组的大小,我将编辑循环。我通常在程序中为数组创建大小函数。它是一个字符串的数组,而不是常量字符*
,因此我不确定是否有nul初始化列表中的ls将起作用。
cout << "Please enter the name of the city you would like to remove: ";
cin >> CityRemove;
for(int i = 0; i < Arr_Size; i++)
{
if(Arr[i] == CityRemove)
{
Arr[i] = Empty; //previous constant to represent your "empty" cell
}
else if(i == Arr_Size - 1) //on last loop, tell the user you could not find it.
{
cout << "Could not find the city to remove, sorry!";
}
}
for(int i = 0; i < Arr_Size; i++)
{
if(Arr[i] != Empty) //if the cell isnt 'empty'
{
cout << Arr[i] << endl;
}
}