I was de-serializing objects that had an extra newline that needed to be removed before getting the next object.
#ifndef THORSANVIL_UTIL_H
#define THORSANVIL_UTIL_H
// Removed headers for getDist() and getRandomContainerIterator()
// We already reviewed those two.
#include <iostream>
namespace ThorsAnvil
{
namespace Util
{
// Removed getDist() and getRandomContainerIterator()
// We already reviewed those two.
class IgnoreUntilNewLine
{
public:
friend std::istream& operator>>(std::istream& stream, IgnoreUntilNewLine& /*data*/)
{
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return stream;
}
};
class SkipEmptyLineToEnd
{
public:
friend std::istream& operator>>(std::istream& stream, SkipEmptyLineToEnd& /*data*/)
{
std::string emptyLine;
std::getline(stream, emptyLine);
if (!emptyLine.empty()) {
stream.setstate(std::ios::badbit);
}
return stream;
}
};
}
}
#endif
Simplified Example for usage:
namespace TU = ThorsAnvil::Util;
struct Example1
{
int x;
int y;
std::string line; // Always one line with no "\n"
void swap(Example1& other) noexcept {/*Stuff*/}
friend std::ostream& operator<<(std::ostream& stream, Example1 const& data)
{
// Note putting a new line here
// to make the Serialized object more readable.
// The actual object was a bit more complicated and
// I really wanted to make it readable.
return stream << data.x << " " << data.y << "\n"
<< data.line << "\n";
}
friend std::istream& operator>>(std::istream& stream, Example1& data)
{
Example1 tmp;
if (stream >> tmp.x >> tmp.y)
{
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (std::getline(stream, tmp.line)) {
data.swap(tmp);
}
}
return stream;
}
};
I thought the above read was a bit cumbersome and hard to read. Thus the two types above. This means I can re-write the read operation as:
friend std::istream& operator>>(std::istream& stream, Example1& data)
{
TU::IgnoreUntilNewLine ignoreNewLine;
Example1 tmp;
if ((stream >> tmp.x >> tmp.y >> ignoreNewLine) && std::getline(stream, tmp.line)) {
data.swap(tmp);
}
return stream;
}