Hi! For one of my assignments, it requires that I code a program that can store, delete, and view an archive of the users favorite games. It's a chapter introducing the use of vectors from the book 'Beginning C++ through game programming'.
Anyway, here is my code. I can't quite figure out why it's returning errors. Very new at this....
Although that completes the assignment, I'd like to know more about how I might remove certain titles from the vector. As it stands 'remove' only removes the last one on the list.
#include <iostream>
#include <string>
#include <vector>
int main()
{
// C++11: http://www.stroustrup.com/C++11FAQ.html#init-list
std::vector< std::string > library { "Halo: 3", "Fable: Lost Chapters", "World of Warcraft" } ;
std::cout << "You have " << library.size() << " games.\n";
std::cout << "\nYour games: \n";
// C++11: http://www.stroustrup.com/C++11FAQ.html#forfor( const std::string& game : library ) std::cout << game << '\n' ;
std::string input ;
do
{
std::cout << "\n\nWhat would you like to do? add/view/remove/quit? ";
std::cin >> input;
if( input == "add" )
{
std::cout << "What would you like to add? ";
std::string game_to_be_added ;
// we want to read in the name of the game which may contain spaces
// so, use std::getline http://en.cppreference.com/w/cpp/io/basic_istream/getline
// before that, we need to extract and discard the new line remaining in the input buffer
// so, std::cin >> std::ws http://en.cppreference.com/w/cpp/io/manip/ws
// more information: http://www.cplusplus.com/forum/general/196903/#msg945238
std::getline( std::cin >> std::ws, game_to_be_added ) ;
library.push_back(game_to_be_added);
}
elseif( input == "view" )
{
std::cout << "\nYou have " << library.size() << " games.\n";
std::cout << "\nYour games: \n";
for( const std::string& game : library ) std::cout << game << '\n' ;
}
elseif( input == "remove" )
{
// can't remove anything from an empty vector
if( library.empty() ) std::cout << "can't remove from empty library\n" ;
// if there is only one game in the library, remove it
elseif( library.size() == 1 ) library.pop_back();
else // ask the user which game is to be removed
{
for( std::size_t i = 0 ; i < library.size() ; ++i )
std::cout << i+1 << ". " << library[i] << '\n' ;
std::size_t pos = 0 ;
std::cout << "which game do you want to remove? [1-" << library.size() << "]? " ;
std::cin >> pos ; // for now, we will assume that the user enters a valid number
--pos ; // make the position zero based
// if the user entered a valid position, remove the item
// http://en.cppreference.com/w/cpp/container/vector/erase (1)
// http://en.cppreference.com/w/cpp/container/vector/beginif( pos < library.size() ) library.erase( library.begin() + pos ) ;
else std::cout << "invalid input\n" ;
}
}
elseif( input != "quit" ) std::cout << "invalid input\n" ;
}
while (input != "quit");
}