implementing simple input stream

萝らか妹 提交于 2019-12-11 01:34:07

问题


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

I want to only implement readline (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
}

回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/5647543/implementing-simple-input-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!