E.Y. February 2016

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

I have a players.txt file where I need to read from and put my readings in a constructor and then I will make a list of these TennisPlayer objects. And I am stuck with how to do it. Well, the first thing is I read from file word by word or line by line but couldn't manage how to put my readings into constructor. My constructor has five inputs:

TennisPlayer(string firstName, tring lastName, int ranking, int totalPoints, string country) 

And part of my players.txt file is here:

Novak Djokovic 16790 Serbia
Andy Murray 8945 Great Britain

And secondly, how can take "Great Britain" as one string?

I am really new in C++ and in a desperate position. Thank you all for your help.

Answers


makar February 2016

Create a stream from a file and then pass it to a class like this. It will iterate over the file, store the values in a vector and then initialise a vector of those objects in the constructor. To read the country, we keep reading in words until we find the end of the line. Therefore, I am working under the assumption that each tennis player is specified in a single line.

Note that there is no error checking here, you may wish to 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 could be several words, keep appending until we have finished
            while (ss.good())
            {
                std::string country_part;
                ss >> country_part;
                if (player.country.empty())
                    player.country += country_part;
                else 
                 

Post Status

Asked in February 2016
Viewed 2,383 times
Voted 9
Answered 1 times

Search




Leave an answer