我想讀整個流(多行)到一個字符串。如何將整個流讀入std :: string?
我使用此代碼,它的工作原理,但它的冒犯我的風格......當然有更簡單的方法嗎?也許使用stringstreams?
void Obj::loadFromStream(std::istream & stream)
{
std::string s;
std::streampos p = stream.tellg(); // remember where we are
stream.seekg(0, std::ios_base::end); // go to the end
std::streamoff sz = stream.tellg() - p; // work out the size
stream.seekg(p); // restore the position
s.resize(sz); // resize the string
stream.read(&s[0], sz); // and finally, read in the data.
其實,一個
const
參照字符串將做的一樣好,而且可能使事情變得更容易...
const std::string &s(... a miracle occurs here...)
如果你想:它可能仍然是一個單線程:'string s = string(...)'。 – 2010-07-08 12:38:37
謝謝。你能詳細說明這是幹什麼嗎?不需要初始化嗎? – Roddy 2010-07-08 12:46:19
@Roddy:該字符串是istreambuf_iterator的範圍結構,它對未格式化的字符進行迭代,直到它變成默認構造的輸入迭代器,即「流的結尾」。請參閱Scott Meyers,Effective STL第29項:考慮istreambuf_iterators逐個字符輸入 – Cubbi 2010-07-08 12:56:43