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

后端 未结 7 964
灰色年华
灰色年华 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:42

    I'm late to the party, but here is a fairly efficient solution:

    std::string gulp(std::istream &in)
    {
        std::string ret;
        char buffer[4096];
        while (in.read(buffer, sizeof(buffer)))
            ret.append(buffer, sizeof(buffer));
        ret.append(buffer, in.gcount());
        return ret;
    }
    

    I did some benchmarking, and it turns out that the std::istreambuf_iterator technique (used by the accepted answer) is actually much slower. On gcc 4.4.5 with -O3, it's about a 4.5x difference on my machine, and the gap becomes wider with lower optimization settings.

    0 讨论(0)
提交回复
热议问题