开发者

implementing simple input stream

开发者 https://www.devze.com 2023-02-24 02:10 出处:网络
I want to write a simple istream object, that would simply transform another istream. I want to only implement r开发者_开发知识库eadline (which would read a line from the original stream, would proce

I want to write a simple istream object, that would simply transform another istream.

I want to only implement r开发者_开发知识库eadline (which would read a line from the original stream, would process it, and return the processed line), and have some generic code that upon read would use my read line, cache it, and give the required amount of bytes as output.

Is there any class that would allow me to do that?

For example

struct mystream : istreamByReadLine {
  istream& s;
  mystream(istream& _s):s(_s){}
  virtual string getline() {
    string line;
    getline(s,line);
    f(line);
    return line;
  }
}

class istreamByReadLine : istream {
  ... // implementing everything needed to be istream compatible, using my
  ... // getline() virtual method
}


Have you looked at boost.iostreams? It does most of the grunt work for you (possibly not for your exact use case, but for C++ standard library streams in general).


Are you sure this is the way to go? In similar cases, I've either defined a class (e.g. Line), with a >> operator which did what I wanted, and read that, e.g.:

Line line
while ( source >> line ) ...

The class itself can be very simple, with just a std::string member, and an operator std::string() const function which returns it. All of the filtering work would be done in the std::istream& operator>>( std::istream&, Line& dest ) function. Or I've installed a filtering streambuf in front of the normal streambuf ; Boost iostream has good support for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号