jeudi 24 septembre 2015

Matching a string at the beginning of a inputstream in C++

I have implemented a simple inputstream manipulator to match the next n chars in an inputstream against a given string. However, I am not sure if this is the best way to do this. Any hints?

class MatchString {
private:
  std::string mString;

public:
  MatchString(const std::string &str) { 
    mString = str; 
  }

  std::istream& operator()(std::istream& is) const {
    // Allocate a string buffer, ...
    char *buffer = new char[mString.length()];

    // ... read next n chars into the buffer ...
    is.read(buffer, mString.length());

    // ... and compare them with given string.
    if(strncmp(buffer, mString.c_str(), mString.length())) {
      throw MismatchException(mString);
    }

    delete[] buffer;

    return is;
  }
};

inline MatchString match(const std::string &str) {
  return MatchString(str);
}

inline std::istream& operator>>(std::istream& is, const MatchString& matchStr) {
  return matchStr(is);
}

Aucun commentaire:

Enregistrer un commentaire