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

前端 未结 6 1031
醉话见心
醉话见心 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:36

    You can do something like the following..

    std::istringstream str;
    str.rdbuf()->pubsetbuf(,);
    

    And then use it in your getline calls...

    NOTE: getline does not understand dos/unix difference, so the \r is included in the text, which is why I chomp it!

      char buffer[] = "Hello World!\r\nThis is next line\r\nThe last line";  
      istringstream str;
      str.rdbuf()->pubsetbuf(buffer, sizeof(buffer));
      string line;
      while(getline(str, line))
      {
        // chomp the \r as getline understands \n
        if (*line.rbegin() == '\r') line.erase(line.end() - 1);
        cout << "line:[" << line << "]" << endl;
      }
    

提交回复
热议问题