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

后端 未结 6 1061
误落风尘
误落风尘 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:21

    std::string has a resize function you could use, or a constructor that'll do the same:

    boost::uint16_t len;
    is.read((char*)&len, 2);
    
    std::string str(len, '\0');
    is.read(&str[0], len);
    

    This is untested, and I don't know if strings are mandated to have contiguous storage.

提交回复
热议问题