Home > Mobile >  Add the elements of a file into a class object
Add the elements of a file into a class object

Time:12-02

I have this file that contains a name cost unit and qty of items that I need to read from and put it into a class object I want each line in the file to be a its own object the file

This is the constructor for my class

Cost::Cost(string name, double cost, string unit, double qty) : Item(name, unit)
{
    this->getName() = name;
    this->cost= cost;
    this->getUnit() = unit;
    this->qty = qty;
}

I tried to do this

ifstream inFile("data.txt");

    string line, word, name, unit;
    double cost = 0.0, qty = 0.0;
    vector<string> itemStr;
    vector<Cost> itemObj;
    

    while (inFile)
    {
        while (getline(inFile, line))
        {
            std::stringstream stream(line);
            while (getline(stream, word, delim))
            {
                itemStr.push_back(word);
            }

            name = itemStr.at(0);
            cost = std::stod(itemStr.at(1));
            unit = itemStr.at(2);
            qty = std::stod(itemStr.at(3));
            

            Cost c(name, cost, unit, qty);

            itemObj.push_back(c);
            
        }
        
    }

but it would only put the first line into the object multiple times when I want each line into its own object

CodePudding user response:

Your bug is here

vector<string> itemStr;
vector<Cost> itemObj;    

while (inFile)
{
    while (getline(inFile, line))
    {
        std::stringstream stream(line);
        while (getline(stream, word, delim))
        {
            itemStr.push_back(word);
        }

it should be

vector<Cost> itemObj;    

while (inFile)
{
    while (getline(inFile, line))
    {
        vector<string> itemStr;
        std::stringstream stream(line);
        while (getline(stream, word, delim))
        {
            itemStr.push_back(word);
        }

In your version the itemStr vector just grows and grows, but you keep reusing the same four elements at the start of the vector, that's why you get the same object added repeatedly. In my version the itemStr vector starts at size zero for each new line.

It's good practice to declare variables as close to where you use them as possible (instead of declaring them at the start of the function). It's cleaner and make bugs like this less likely.

You can also remove the while (inFile) loop which does nothing.

  • Related