Thanks in advance for your help. I am writing a program that is supposed to display a menu and ask the user to enter a list of his/her favorite games, then display the games if they choose to. The problem is that when it comes to entering the names of the games, it automatically enters a null value in the first element of the vector. I've tried to put a cin.ignore(), but if the string contains a space and a number at the end, the program will interpret that number as something else and spit out the error for inputting the menu choices. Here is my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> list;
int main()
{
int num;
int fav;
string g;
char ag;
//display menu
cout << "Welcome to Your Favorite Games List Generator." << endl;
cout << "Here is the Menu:" << endl << endl;
cout << "1) Enter games into your list." << endl;
cout << "2) Display your list." << endl;
cout << "3) Quit." << endl;
cout << endl;
cout << "What would you like to do?" << endl;
cin >> num; //get user's input from menu choices
cout << endl;
while(1)
{
if(cin.fail()) //validate user input
{
cin.clear();
cin.ignore(100, '\n');
cout << "I'm sorry. You can only enter numbers 1-3 here." << endl;
cout << "\nWhat would you like to do?" << endl;
cin >> num;
continue;
}
break;
}
switch(num)
{
case 1: cout << "Great. How many favorite games do you have?" << endl;
cin >> fav; //get number of favorite games
cout << endl;
cout << "Would you like to enter your games?" << endl;
cin >> ag; //establish condition for loop
do
{
for(int x = 0; x < fav; x++)
{
cout << "Enter game: \n";
getline(cin, g); //get names of games
list.push_back(g); //store names in a vector
}
cout << "Would you like to enter another game?" << endl;
cin >> ag; // ask if user is done
}while(ag == 'y' || ag == 'Y'); //end loop
if(ag != 'y' || ag != 'Y') //if user is done, return to the menu
{
cout << "\n\nOk. Thanks for entering your games." << endl;
cout << endl;
main();
}
break;
case 2: if(list.empty()) //check for an empty vector
{
cout << "I'm sorry. You can't display a list that hasn't" << endl;
cout << "been created yet. Choose either #1 or #3." << endl;
cout << endl;
main();
}
for(int i = 0; i < list.size(); i++) //display list of names
{
cout << list[i];
cout << endl;
}
break;
case 3: exit(0); //exit the program
}
system("pause");
return (0);
}