-
Overloaded >>
I need to use the overloaded >> this way
Code:
// while "std::cin >> process" is succesfull
while (std::cin >> process && !(ph.isFull())) {
// do something
}
Code:
std::istream &operator>>(std::istream &stream, PCB &pcb)
char* temp = new char[MAX_HOOK_LEN]; // Temporary holder for process info
stream >> pcb.pid;
if (pcb.pid == -1) { // '-1' indicates end of input
return ???? //what to return
}
stream >> pcb.arrival_time;
stream >> pcb.last_cpu_burst;
stream >> pcb.test_cpu_burst;
stream >> pcb.priority;
stream >> pcb.state_status;
if (stream.getline(temp, MAX_HOOK_LEN, '\n')){
pcb.hook = temp;
}
return stream;
}
-
What you return is a reference to an istream (naturally), before you return you set the failbit to indicate that you could not read a new record, and eofbit to indicate that you cannot read another record because you have read them all.
Code:
std::istream &operator>>(std::istream &stream, PCB &pcb)
PCB temp;
stream >> temp.pid;
if(temp.pid == -1) {
stream.setstate(std::ios_base::failbit | std::ios_base::eofbit);
return stream;
}
stream >> temp.arrival_time;
stream >> temp.last_cpu_burst;
stream >> temp.test_cpu_burst;
stream >> temp.priority;
stream >> temp.state_status;
getline(stream,temp.hook);
if(stream) pcb.swap(temp);
return stream;
}
This assumes that PCB uses a std::string for it's hook, otherwise you have a memory leak in your previous code. This also obeys the convention that I always use that all >> operations leave thier targets unchanged. swap() is a new member that makes this and many other things much easier.
-
hhmmm, interesting makeover you did there
thanks for the new knowledge and insight