given 1 stringstream object, copy another. according :
how copy 1 stringstream object in c++?
(among others), proper way use rdbuf()
member. however, seems cause issues, particularly if stringstream const.
for example:
void dosomething(stringstream & ss) { stringstream sstmp; cout << "pos 1: " << ss.tellg() << "\n"; sstmp << ss.rdbuf(); cout << "pos 2: " << ss.tellg() << "\n"; // sstmp.rdbuf()->pubseekpos(0, ios_base::in | ios_base::out); cout << "string: " << sstmp.str() << "\n"; } int main(void) { stringstream ss; ss << "hello"; dosomething(ss); dosomething(ss); return 0; }
the output is
pos 1: 0 pos 2: 5 string: hello pos 1: 5 pos 2: 5 string:
the first call dosomething()
changed internal pointer, , seems if stringstream
const (left out here tellg()
not const). way remedy seekg()
, can't called on const streams. attempted way (commented out in code) without success.
so can done either:
copy (const)
stringstream
without changing it, orreset position on const object?
note: compiled using gcc 4.8.1 on arch linux
the straightforward way make string , copy way: sstmp.str(ss.str());
the less obvious approach utilize fact can gain non-const access rdbuf
const stringstream.
i made several changes code compiles, , updated code directly set rdbuf
's position, should want, outputting:
string: hello string: hello
-
#include <sstream> #include <iostream> void dosomething(const std::stringstream& ss) { std::stringstream sstmp; sstmp << ss.rdbuf(); ss.rdbuf()->pubseekpos(0, std::ios_base::in); std::cout << "string: " << sstmp.str() << "\n"; } int main() { std::stringstream ss; ss << "hello"; dosomething(ss); dosomething(ss); return 0; }
Comments
Post a Comment