Hey, i'm new to C++, i've been reading though Beginning C++ Game Programming and the exercise for chapter 4 was to create a program with stores the user's favourite games. I've completed the program, but if a user puts a space between two words when naming themselves or adding a game, the program will go into a infinite loop for some reason :/
Posted the code below, it's not really that important, just wanted to know why it has done this.
// favourite games list
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
vector<string> gamesList;
gamesList.push_back("GTA");
gamesList.push_back("Oblivion");
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
string playerName;
cout << "Initilizing...";
cout << "\n\nHello and welcome to your personal games list ('5' for disclaimer)";
cout << "\nPlease enter your name (NO SPACES): ";
cin >> playerName;
int choice;
while (choice != 4)
{
cout << "\nThis is " << playerName << "'s game list!";
cout << "\nMain Menu:";
cout << "\n1 - View games";
cout << "\n2 - Add a game";
cout << "\n3 - Erase last game";
cout << "\n4 - Exit";
cout << "\nPlease select an option: ";
cin >> choice;
switch (choice)
{
case 1:
for (iter = gamesList.begin(); iter != gamesList.end(); ++iter)
{
cout << " - ";
cout << *iter << endl;
}
break;
case 2:
{
cout << "\nType the name of the game you want to add (NO SPACES): ";
string newGame;
cin >> newGame;
gamesList.push_back(newGame);
cout << "\n" << newGame << " added to your favourites.\n";
}
break;
case 3:
if (gamesList.size() >= 1)
{
cout << "\nYou have removed the last item from your list\n";
gamesList.pop_back();
}
else
cout << "\nYou have no games to delete!\n";
break;
case 4:
continue;
case 5:
cout << "\n\n*Mostly working game indexer, apart from when you add";
cout << "\nspaces in the name or game name, it crashes :/";
default:
cout << "\nPlease enter a valid choice\n";
}
}
return 0;
}
When you use formatted input (like cin), you'll only get one token per variable in your line. And, since cin is buffered, you won't return from it until you get an endline or fill all the variables in the cin line.
When you enter a space on the input line, you're creating multiple tokens. cin won't return until one of the above conditions are met.
Sure...you can use getline(). You have a lot more control over your input processing; the trade-off is that you have to do your own conversions. In my experience, though, most programmers who want to write "user-proof" code use getline() instead of relying on cin.
Glad to hear it. It occurred to me that I might have tossed a few cobblers in the details of my explanation, but the gist is valid: use getline() when you need some control over the user input.