如何将用户输入添加到数组或删除?C

How to add user input to array or remove it? C++

本文关键字:数组 删除 添加 用户 输入      更新时间:2023-10-16

说我获取用户输入。如果它们输入的内容尚未在数组中(我该如何检查数组?),请将其添加到数组中。反之亦然,我如何从给定用户输入的数组中删除一些内容。

示例:

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;

内置数组的大小是不变的:您既不能删除元素,否则您无法添加任何元素。我建议使用std::vector<std::string>,而是:将元素添加到std::vector<T>可以使用push_back()完成。要删除元素,您将找到一个元素,例如,使用std::find(),然后使用erase()删除它。

如果您需要使用内置阵列(尽管我看不出有任何充分理由),则您将使用new std::string[size]在堆上分配一个数组并保持其尺寸,并使用delete[] array;在适当的时间释放内存。

使用数组,您可以用char*(例如"空")处理空数组单元格。要查找您在数组中搜索的项目,然后查找"替换"或添加。

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!";
}

至于删除单元格:

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

但我确实同意使用向量是一种更有效的方法,这只是一种创造性的方法来吸引您的思维思维。

要在数组中添加信息,您可以做这样的事情:

for (int i = 0; i < 10; i++)
{
    std::cout << "Please enter the city's name: " << std::endl;
    std::getline(cin, myArray[i]);
}

我不确定从数组中删除某些内容是什么意思。您是否要将元素的值设置为0,这将导致{"城市1","城市2",0,"城市3}"。要填充其空间,这将导致{"城市1","城市2","城市3"}?