How can I print a list of structs that contain two members?

I created a struct and put two member variables in it. Then initialized a list with the mentioned struct type.

struct job {
    string name;
    int time;
};

list<job> jobList;

string line;
ifstream file("input.txt");  // the direction of my input file.
if (file.is_open()) {
    while (getline(file, line)) {
        string col1;
        int col2;
        istringstream ss(line);
        ss >> col1 >> col2;
        job a;
        a.name = col1;
        a.time = col2;

        jobList.push_back(a);
    }
}

Now I want to know, how can I print my jobList? Whatever I do, does not work and I get errors.

I used the following function to print my list contents:

for (auto v : jobList)
    std::cout << v << "n";
}

The error I get is:

Invalid operands to binary expression (‘std::__1::ostream’ (aka ‘basic_ostream<char>’) and ‘job’)

I think that is because my struct has two variables (name and time) but I am not sure. The purpose of printing jobList is to make sure that I have created my list properly.

After printing, the output should be as follows:

MPL 3
JOB 1
CORE 50
DISK 10
CORE 150
DISK 0
CORE 100
DISK 0

Answer

The problem with:

for (auto v : jobList)
    std::cout << v << "n";
}

is that v is a job structure, and you have no stream output operator overloaded for job.

There are two possible solutions:

  1. Output the members one by one:

    for (auto const& v : jobList) {
        std::cout << v.name << " - " << v.time << 'n';
    }
    
  2. Create an overloaded operator for outputting the structure:

    std::ostream& operator<<(std::ostream& os, job const& j)
    {
        return << v.name << " - " << v.time;
    }
    
    ...
    
    for (auto const& v : jobList) {
        std::cout << v << 'n';
    }
    

Leave a Reply

Your email address will not be published. Required fields are marked *