From 190a30495e2d9af10a6b4a4f70bc51c68847ad1a Mon Sep 17 00:00:00 2001 From: Johann Dreo Date: Mon, 30 Sep 2024 20:42:20 +0200 Subject: [PATCH] fix(EO): allow readFrom to work on std::cin + invalidTag - std::cin does not allow seekg/tellg, so instead one wrap the read string in a istringstream, and then read from it. This allows to read from any istream, with or without seekg. - Adds an EO::invalidTag member, in case someone would need to use it (for instance as a regexp to sanitize inputs). --- eo/src/EO.h | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/eo/src/EO.h b/eo/src/EO.h index a2c3b490a..09bb2d20d 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -64,6 +64,8 @@ template class EO: public eoObject, public eoPersistent public: typedef F Fitness; + static constexpr const char* invalidTag = "INVALID"; + /** Default constructor. */ EO(): repFitness(Fitness()), invalidFitness(true) { } @@ -124,25 +126,21 @@ template class EO: public eoObject, public eoPersistent * The read and print methods should be compatible and have the same format. * In principle, format is "plain": they just print a number * @param _is a std::istream. - * @throw eoInvalidFitnessError If a valid object can't be read. */ - virtual void readFrom(std::istream& _is) { - - // the new version of the reafFrom function. - // It can distinguish between valid and invalid fitness values. + virtual void readFrom(std::istream& _is) + { std::string fitness_str; - int pos = _is.tellg(); _is >> fitness_str; - if (fitness_str == "INVALID") + if (fitness_str == invalidTag) { invalidFitness = true; } else { invalidFitness = false; - _is.seekg(pos); // rewind - _is >> repFitness; + std::istringstream iss(fitness_str); + iss >> repFitness; } } @@ -150,12 +148,11 @@ template class EO: public eoObject, public eoPersistent * Write object. Called printOn since it prints the object _on_ a stream. * @param _os A std::ostream. */ - virtual void printOn(std::ostream& _os) const { - - - // the latest version of the code. Very similar to the old code - if (invalid()) { - _os << "INVALID "; + virtual void printOn(std::ostream& _os) const + { + if (invalid()) + { + _os << invalidTag << ' '; } else {