Skip to content

Commit

Permalink
fix(EO): allow readFrom to work on std::cin + invalidTag
Browse files Browse the repository at this point in the history
- 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).
  • Loading branch information
jdreo committed Sep 30, 2024
1 parent 8ea6e2b commit 190a304
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions eo/src/EO.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ template<class F = double> class EO: public eoObject, public eoPersistent
public:
typedef F Fitness;

static constexpr const char* invalidTag = "INVALID";

/** Default constructor.
*/
EO(): repFitness(Fitness()), invalidFitness(true) { }
Expand Down Expand Up @@ -124,38 +126,33 @@ template<class F = double> 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;
}
}

/**
* 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
{
Expand Down

0 comments on commit 190a304

Please sign in to comment.