getting user input with spaces

SO I am working through some exercises and I have made a list program that uses vectors and iterators to create a list of games a user has. He can add/delete/list the games he has.

Everything works as except for when the user inputs a game that has a space in the title. I am guessing it is an issue with cin? or is there a way to fix this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <string>
#include <cctype>

using namespace std;

void getUserInput(string &userInput);

int main()
{
	vector<string> gamesList;
	string userInput;
	vector<string>::iterator myIterator;
	vector<string>::const_iterator iter;
	//ask user what they want to do - add - delete or list games
	
	while (true)
	{ 
		cout << "\nWhat would you like to do?\nAdd - List or Delete?\n";
		//get user input
		getUserInput(userInput);
		//if user says add
		if (userInput == "add" || userInput == "a")
		{
			cout << "\nWhat game would you like to add?\n";
			//take string and push it to vector
			getUserInput(userInput);
			gamesList.push_back(userInput);
		}
		//if user says delete
		else if (userInput == "delete" || userInput == "d")
		{
			cout << "\nWhich game would you like to delete?\n";
				getUserInput(userInput);
			//take string and remove it
				iter = find(gamesList.begin(), gamesList.end(), userInput);
				if (iter != gamesList.end())
				{
					gamesList.erase(iter);
				}
				else
				{
					cout << "\nThat game is not on the list\n";
				}
		}
		//if user syas list
		else if (userInput == "list" || userInput == "l")
		{ 
			//list hwat is in the list
			if (gamesList.empty())
			{
				cout << "\nThe list is empty\n";
			}
			else
			{
				for (iter = gamesList.begin(); iter != gamesList.end(); ++iter)
				{
					cout << *iter << endl;
				}
			}
		}
		else
		{
			cout << "\nNOT A VALID CHOICE\nadd, list or delete\n";
		}

		cin.clear();
	}

}
void getUserInput(string &userInput)
{
	cin >> userInput;
}


When I add a game and type "max payne" for example it adds max to the vector and outputs on the screen "NOT A VALID CHOICE." I assume the program loops after max has been added and uses payne for the next input?

is there away I can do this better or fix it?
Thanks

Change your getUserInput function to:

1
2
3
4
void getUserInput(string &userInput)
{
   std::getline(std::cin, userInput);
}
Last edited on
Topic archived. No new replies allowed.