How to read from a file to constructor in C++? -


i have players.txt file need read , put readings in constructor , make list of these tennisplayer objects. , stuck how it. well, first thing read file word word or line line couldn't manage how put readings constructor. constructor has 5 inputs:

tennisplayer(string firstname, tring lastname, int ranking, int totalpoints, string country)  

and part of players.txt file here:

novak djokovic 16790 serbia andy murray 8945 great britain 

and secondly, how can take "great britain" 1 string?

i new in c++ , in desperate position. thank help.

create stream file , pass class this. iterate on file, store values in vector , initialise vector of objects in constructor. read country, keep reading in words until find end of line. therefore, working under assumption each tennis player specified in single line.

note there no error checking here, may wish add that

    class tennisplayerslist     {     public:         struct tennisplayer         {             std::string first_name;             std::string second_name;             int ranking;             int total_points;             std::string country;         };          tennisplayerslist(std::istream& filestream)             :players(readplayersfromfile(filestream))         {}     private:         std::vector<tennisplayer> players;          static std::vector<tennisplayer> readplayersfromfile(std::istream& filestream)         {             std::vector<tennisplayer> p;             while (filestream.eof() == false)             {                 p.push_back(readplayer(filestream));             }             return p;         }          static tennisplayer readplayer(std::istream& filestream)         {             using namespace std;             tennisplayer player;             std::string line;             getline(filestream, line);              std::stringstream ss(line);              ss >> player.first_name;             ss >> player.second_name;             ss >> player.ranking;             ss >> player.total_points;              // country several words, keep appending until have finished             while (ss.good())             {                 std::string country_part;                 ss >> country_part;                 if (player.country.empty())                     player.country += country_part;                 else                      player.country += " " + country_part;             }             return player;         }     }; 

call this

std::fstream players; players.open("tennis_players.txt", std::ios::in); tennisplayerslists list(players); players.close(); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -