0

I am trying to get my code for when it gets to the delete option i can type the name of the game it deletes it unfortunately it ony deletes when the number of the game is type not the name. Here is my code please help me i cant firgure it out:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	vector<string> games;
	int choice = 0;
    
	cout << "1. List of Games\n";
	cout << "2. Add a Game you have played\n";
	cout << "3. Remove a Game\n";
	cout << "4. Quit\n";
    
	
	while(choice != 4)
	{
		switch(choice)
		{
			case 0:
			{
				cout << "Choose an option: ";
					cin >> choice;
			}
			break;

			case 1:
			{
				for(unsigned int i = 0; i < games.size(); ++i)
					cout << games[i] << endl;
				choice = 0;
			}
			break;

			case 2:
			{
				cout << "Enter a game to add:(nospaces)";
				string game;
				cin >> game;
				games.push_back(game);
				choice = 0;
			}
			break;

			case 3:
			{
				cout << "Your game so far:\n";
				for(unsigned int i = 0; i < games.size(); ++i)
					cout << i << ". " << games[i] << endl;
				cout << "Enter game to remove: ";
				int remove;
				cin >> remove;
				games.erase(games.begin() + remove);
				choice = 0;
			}
			break;

			
		}
	}

	
	cout << " You selected Quit.\n";
    
	return 0;
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Radical Edward
0

> it ony deletes when the number of the game is type not the name
The number of the game matches the index in your vector. If you want the user to type the name of the game and delete it, you need to search for the name and return the index:

cout << "Your game so far:\n";

for (unsigned int i = 0; i < games.size(); ++i)
  cout << i << ". " << games[i] << endl;

cout << "Enter game to remove: ";

string name;

if (getline(cin, name)) {
  unsigned int i;

  // Find the game to remove
  for (i = 0; i < games.size(); ++i) {
    if (games[i] == name)
      break;
  }

  // i == games.size() if the name wasn't found
  if (i < games.size())
    games.erase(games.begin() + i);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.