我尝试获取用户选择的游戏名称并将其存储在向量中。我使用 getline 以便用户可以使用空格。当我尝试键入要添加的新游戏时,它不会让我这样做。它会自动显示我的游戏库。请告诉我我做错了什么。问题在于 if(action == "add")
这是我的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
vector<string>::const_iterator myIterator;
vector<string>::const_iterator iter;
vector<string> games;
games.push_back("Crysis 2");
games.push_back("GodOfWar 3");
games.push_back("FIFA 12");
cout <<"Welcome to your Games Library.\n";
cout <<"\nThese are your games:\n";
for (iter = games.begin(); iter != games.end(); ++iter)
{
cout <<*iter <<endl;
}
//the loop!
string action;
string newGame;
cout <<"\n-Type 'exit' if you want to quit.\n-Type 'add' if you want to add a game.\n-Type 'delete' if you want to delete a game.\n-Type 'find' if you want to search a game.\n-Type 'game' if you don't know what game to play.\n-Type 'show' if you want to view your library.";
while (action != "exit")
{
cout <<"\n\nWhat do you want to do: ";
cin >> action;
//problem is here
if (action == "add")
{
cout <<"\nType the name of the game you want to add: ";
getline (cin, newGame);
games.push_back(newGame);
for (iter = games.begin(); iter != games.end(); ++iter)
{
cout <<*iter <<endl;
}
continue;
}
else if (action == "show")
{
cout <<"\nThese are your games:\n";
for (iter = games.begin(); iter != games.end(); ++iter)
{
cout <<*iter <<endl;
}
}
else if (action == "delete")
{
cout <<"Type the name of the game you want to delete: ";
cin >> newGame;
getline (cin, newGame);
iter = find(games.begin(), games.end(), newGame);
if(iter != games.end())
{
games.erase(iter);
cout <<"\nGame deleted!";
}
else
{
cout<<"\nGame not found.";
}
continue;
}
else if (action == "find")
{
cout <<"Which game you want to look for in your library: ";
cin >> newGame;
getline (cin, newGame);
iter = find(games.begin(), games.end(), newGame);
if (iter != games.end())
{
cout << "Game found.\n";
}
else
{
cout << "Game not found.\n";
}
continue;
}
else if (action == "game")
{
srand(static_cast<unsigned int>(time(0)));
random_shuffle(games.begin(), games.end());
cout << "\nWhy don't you play " << games[0];
continue;
}
else if (action == "quit")
{
cout <<"\nRemember to have fun while gaming!!\n";
break;
}
else
{
cout <<"\nCommand not found";
}
}
return 0;
}