How to read entire stream into a std::string?

后端 未结 7 963
灰色年华
灰色年华 2020-11-29 19:15

I\'m trying to read an entire stream (multiple lines) into a string.

I\'m using this code, and it works, but it\'s offending my sense of style... Surely there\'s an

相关标签:
7条回答
  • 2020-11-29 19:20

    Well, if you are looking for a simple and 'readable' way to do it. I would recomend add/use some high level framework on your project. For that I's always use Poco and Boost on all my projects. In this case, with Poco:

        string text;
        FileStream fstream(TEXT_FILE_PATH);
        StreamCopier::copyToString(fstream, text);
    
    0 讨论(0)
  • 2020-11-29 19:24

    You could do

    std::string s;
    std::ostringstream os;
    os<<stream.rdbuf();
    s=os.str();
    

    but I don't know if it's more efficient.

    Alternative version:

    std::string s;
    std::ostringstream os;
    stream>>os.rdbuf();
    s=os.str();
    
    0 讨论(0)
  • 2020-11-29 19:25

    Perhaps this 1 line C++11 solution:

    std::vector<char> s{std::istreambuf_iterator<char>{in},{}};
    
    0 讨论(0)
  • 2020-11-29 19:27

    You can try using something from algorithms. I have to get ready for work but here's a very quick stab at things (there's got to be a better way):

    copy( istreambuf_iterator<char>(stream), istreambuf_iterator<char>(), back_inserter(s) );
    
    0 讨论(0)
  • 2020-11-29 19:30

    What about to use getline with delimiter? The next code helps me to read whole std::cin into string on ubuntu with g++-10.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
        string s;
    
        getline(cin, s, {}); //the whole stream into variable s
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 19:39

    How about

    std::istreambuf_iterator<char> eos;
    std::string s(std::istreambuf_iterator<char>(stream), eos);
    

    (could be a one-liner if not for MVP)

    post-2011 edit, this approach is now spelled

    std::string s(std::istreambuf_iterator<char>(stream), {});
    
    0 讨论(0)
提交回复
热议问题