(1) Be cautious of
The std::endl will flush the output buffer while
'\n' not. For example, in socket programming, if client sends message to server using
'\n', like this:
out << "Hello World!" << '\n'; out << "I am coming" << '\n';
The server may still block in reading operation and no data is fetched. So you should use
std::endl in this case:
out << "Hello World!" << std::endl; out << "I am coming" << std::endl;
std::ios::rdstate is a handy function to check the stream state. You can use it in
(gdb) p in.rdstate() $45 = std::_S_goodbit (gdb) n 350 return in; (gdb) p in.rdstate() $46 = std::_S_failbit
Through step-mode, we can see which operation crashes the stream.
(3) Serialize the data into file.
No matter you want to do test or debug issue, dump the data into a file and read it back is a very effective method:
std::ofstream ofs("data.txt"); ofs << output; ofs.close(); std::ifstream ifs("data.txt"); ifs >> input; ifs.close();
The above simple code can verify whether your serialization functions are correct or not. Trust me, it is a very brilliant trouble-shouting std::iostream issue trick, and it saved me just now!