Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

Say I get user input. If what they type in is not already in the array(how do I check an array?), add it to the array. And vice versa how do I remove something from an array given the user input.

Example:

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;
like image 721
user1756669 Avatar asked Mar 24 '26 09:03

user1756669


1 Answers

The size of built-in arrays is immutable: You can neither remove elements not can you add any. I would recommend using a std::vector<std::string>, instead: Adding elements to a std::vector<T> can, e.g., be done using push_back(). To remove an element you would locate an element, e.g., using std::find(), and then use erase() to remove it.

If you need to use built-in arrays (although I don't see any good reason for this), you'd allocate an array on the heap using new std::string[size] and maintain its size, appropriately releasing memory at opportune times using delete[] array;.

like image 197
Dietmar Kühl Avatar answered Mar 26 '26 22:03

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!