I am taking my first C++ class, so I'm sure there are better ways for doing what I am attempting to do. I am trying to populate a vector<string> with input from a user. Everything works great as long as the input is 1 word. If the input contains a space then the program goes weird on me. Nonetheless, here is what I have done. I declared the follow (at the beginning of program):
I then asked the user to enter a number from a menu and then used a switch. So far, it is the following case that doesn't work (hope there are no more).
case CREATE:
{
char again;
do
{
cout << "\nPlease enter a game title for your list: ";
cin >> gameName;
favList.push_back(gameName);
cout << "\nWould you like to enter another game title(y/n)? ";
cin >> again;
} while (again == 'y');
break;
}
My textbook only shows examples of single words being used. How do I allow the use to enter a gameName that is more than one word?
Something that C++ teachers and textbooks almost invariably fail to teach at the outset is that >> is for formatted input. People use it all the time for general input but that is often a bad idea (at least until you know what you are doing).
To get unformatted string input from the user, up-to his pressing the Enter key, use the <string> getline() function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <cctype>
#include <iostream>
#include <limits>
#include <string>
usingnamespace std;
...
string gameName;
char again;
do
{
cout << "\nPlease enter a game title for your list: ";
getline( cin, gameName );
favList.push_back( gameName );
cout << "\nWould you like to enter another game title(y/n)? ";
cin >> again;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
} while (toupper( again ) == 'Y');
This demonstrates two things: getting an unformatted string (automatically reads the '\n' and discards it), and getting a formatted input (a char). The character input is immediately followed by cin.ignore() in order to read everything up-to and including the '\n' and discard it.
This makes sure your input stream is ready for the next input, whether it be an unformatted string input or a formatted char/int/whatever input. In this example, it also allows the user to enter things like "yes" without choking. If you only want a single character before the user hits Enter, you could just say: cin >> ws;
to read (and discard) all whitespace (including that unread '\n' sitting in the input buffer).