views:

19

answers:

2

I'm trying to find an elegant way to parse a string like:

EVENT_TYPE(param1;param2; ...)

EVENT_TYPE is one of many string constants, each has zero or more parameters. So far I thought that given the sting "s" contains EVENT_TYPE(param1;param2) I'd write:

if (boost::istarts_with(s, "EVENT_TYPE")) {
  std::istringstream iss(s);
  int param1, param2;
  iss >> "EVENT_TYPE(" >> param1 >> ";" >> param2 >> ")";
}

That would be nice to give a const string& and tell that way "skip these characters". Well, that's not the case. How would YOU THERE go about this? :-)

Thanks for advice!

A: 

This looks complicated enough to warrant a "real" parser. Since you're already using Boost, try this first: http://boost-spirit.com/home/

Zack
A: 

Um, off the top of my head:

// Beware, brain-compiled code ahead!
class string_const {
public:
  string_const(const std::string& str) : str_(str) {}
  void read(std::istream& is) const
  {
    is >> std::ws; // if leading whitespace ok
    for(std::string::size_type idx=0; idx<str_.size(); ++idx) {
      char ch;
      if(!(is >> ch))
        return;
      if(ch != str_[idx]) {
        str.setstate(std::ios:failbit);
        return;
      }
    }
  }
private:
  std::string str_;
};

inline std::istream& operator>>(std::istream& is, const string_const& str)
{
  str.read(is);
  return is;
}

Use it like this:

iss >> string_const("EVENT_TYPE(") >> ...;
sbi