Reading directly from an std::istream into an std::string

后端 未结 6 1058
误落风尘
误落风尘 2020-11-30 08:00

Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so?

eg currently I can do it by



        
6条回答
  •  被撕碎了的回忆
    2020-11-30 08:17

    You could use a combination of copy_n and an insert_iterator

    void test_1816319()
    {
        static char const* fname = "test_1816319.bin";
        std::ofstream ofs(fname, std::ios::binary);
        ofs.write("\x2\x0", 2);
        ofs.write("ab", 2);
        ofs.close();
    
        std::ifstream ifs(fname, std::ios::binary);
        std::string s;
        size_t n = 0;
        ifs.read((char*)&n, 2);
        std::istream_iterator isi(ifs), isiend;
        std::copy_n(isi, n, std::insert_iterator(s, s.begin()));
        ifs.close();
        _unlink(fname);
    
        std::cout << s << std::endl;
    }
    

    no copying, no hacks, no possibility of overrun, no undefined behaviour.

提交回复
热议问题