How can I read from memory just like from a file using iostream?

前端 未结 6 1041
醉话见心
醉话见心 2020-12-09 12:41

I have simple text file loaded into memory. I want to read from memory just like I would read from a disc like here:

ifstream file;
string line;

file.open(\         


        
6条回答
  •  孤街浪徒
    2020-12-09 13:29

    I found a solution that works on VC++ since Nim solution works only on GCC compiler (big thanks, though. Thanks to your answer I found other answers which helped me!).

    It seems that other people have similar problem too. I did exactly as here and here.

    So to read from a piece of memory just like form a istream you have to do this:

    class membuf : public streambuf
    {
        public:
            membuf(char* p, size_t n) {
            setg(p, p, p + n);
        }
    };
    
    int main()
    {
        char buffer[] = "Hello World!\nThis is next line\nThe last line";  
        membuf mb(buffer, sizeof(buffer));
    
        istream istr(&mb);
        string line;
        while(getline(istr, line))
        {
            cout << "line:[" << line << "]" << endl;
        }
    }
    

    EDIT: And if you have '\r\n' new lines do as Nim wrote:

    if (*line.rbegin() == '\r') line.erase(line.end() - 1);
    

    I'm trying to treat this memory as as wistream. Does anybody know how to do this? I asked separate question for this.

提交回复
热议问题