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
2
Answers
You can print the individual struct members in your range-for loop:
The problem with:
is that
v
is ajob
structure, and you have no stream output operator overloaded forjob
.There are two possible solutions:
Output the members one by one:
Create an overloaded operator for outputting the structure: