Code Sample – Simple Text Parser

//START OF HEADER FILE (INTERFACE)
//----------------------------------------------------------

class Parser
{
  public:

    Parser(std::istream &input);
  
    Parser      &consume(const std::string &token);
    float        readFloat(void);
    Parser      &readFloat(float &dest);
    int          readInt(void);
    Parser      &readInt(int &dest);
    unsigned     readUnsigned(void);
    Parser      &readUnsigned(unsigned &dest);
    std::string  readString(void);
    Parser      &readString(std::string &dest);

    Parser &operator()(const std::string &token);
    Parser &operator()(float             &dest );
    Parser &operator()(int               &dest );
    Parser &operator()(unsigned          &dest );
    Parser &operator()(std::string       &dest );

  private:
  
    std::istream &input_;
};

//----------------------------------------------------------
//END OF HEADER FILE


//START OF SOURCE FILE (IMPLEMENTATION)
//----------------------------------------------------------

Parser::Parser(std::istream &input)
  : input_(input)
{ }

Parser &Parser::consume(const std::string &token)
{
  //consume preceeding white spaces
  while (1)
  {
    if (std::isspace(input_.peek())) input_.get();
    else break;
  }

  //start consuming token
  for
  (
    unsigned index = 0, len = token.size(); 
    index < len; ++index
  )
  {
    if (input_.get() != token.at(index))
    {
      //replace this with custom failure handling logic
      __asm int 3;
    }
  }

  return *this;
}

float Parser::readFloat(void)
{
  float f;
  input_ >> f;
  return f;
}

Parser &Parser::readFloat(float &dest)
{
  input_ >> dest;
  return *this;
}

int Parser::readInt(void)
{
  int i;
  input_ >> i;
  return i;
}

Parser &Parser::readInt(int &dest)
{
  input_ >> dest;
  return *this;
}

unsigned Parser::readUnsigned(void)
{
  unsigned u;
  input_ >> u;
  return u;
}

Parser &Parser::readUnsigned(unsigned &dest)
{
  input_ >> dest;
  return *this;
}

std::string Parser::readString(void)
{
  std::string s;
  consume("\"");
  char current;
  while ((current = input_.get()) != '\"')
  {
    s += current;
  }
  return s;
}

Parser &Parser::readString(std::string &dest)
{
  dest = "";
  consume("\"");
  char current;
  while ((current = input_.get()) != '\"')
  {
    dest += current;
  }
  return *this;
}

Parser &Parser::operator()(const std::string &token)
{
  return consume(token);
}

Parser &Parser::operator()(float &dest)
{
  return readFloat(dest);
}

Parser &Parser::operator()(int &dest)
{
  return readInt(dest);
}

Parser &Parser::operator()(unsigned &dest)
{
  return readUnsigned(dest);
}

Parser &Parser::operator()(std::string &dest)
{
  return readString(dest);
}

//----------------------------------------------------------
//END OF SOURCE FILE

Leave a Reply