Search code examples
c++ifstream

C++: reading in from a text file


I'm trying to figure out the best way to read in a .txt file, with comma separated information, line separated. Using that information, to create objects of my stock class.

.txt file looks like this:

    GOOGL, 938.85, 30
    APPL, 506.34, 80
    MISE, 68.00, 300

My stock class constructor is like stock(string symbol, double price, int numOfShares);

In my main program, I want to set up an input file stream that will read in the information and create objects of stock class, like so:

stock stock1("GOOGL", 938.85, 30);

stock stock2("APPL", 380.50, 60);

I assume I use ifstream and getline, but not quite sure how to set it up.

Thanks!


Solution

  • #include <fstream>
    #include <string>
    #include <sstream>
    
    int main()
    {
        //Open file
        std::ifstream file("C:\\Temp\\example.txt");
    
        //Read each line
        std::string line;
        while (std::getline(file, line))
        {
            std::stringstream ss(line);
            std::string symbol;
            std::string numstr;
            //Read each comma delimited string and convert to required type
            std::getline(ss, symbol, ',');
            std::getline(ss, numstr, ',');
            double price = std::stod(numstr);
            std::getline(ss, numstr, ',');
            int numOfShares = std::stoi(numstr);
    
            //Construct stock object with variables above
            stock mystock(symbol, price, numOfShares);
        }
    
        return 0;
    }