一个流缓冲的内容复制到一个字符串 [英] Copy a streambuf's contents to a string
问题描述
显然提高:: ASIO :: async_read
不喜欢字符串,如提振唯一的过载:: ASIO ::缓冲
允许我创建 const_buffer
S,所以我坚持与阅读一切都变成流缓冲。
现在我想的streambuf的内容复制到一个字符串,但它显然只支持写入为char *( sgetn()
),创建具有流缓冲的istream和使用函数getline()
。
Apparently boost::asio::async_read
doesn't like strings, as the only overload of boost::asio::buffer
allows me to create const_buffer
s, so I'm stuck with reading everything into a streambuf.
Now I want to copy the contents of the streambuf into a string, but it apparently only supports writing to char* (sgetn()
), creating an istream with the streambuf and using getline()
.
是否有任何其他的方法来创建具有的streambuf内容的字符串没有过多的复制?
Is there any other way to create a string with the streambufs contents without excessive copying?
推荐答案
我不知道这是否算作过度复制的,但您可以使用一个字符串流:
I don't know whether it counts as "excessive copying", but you can use a stringstream:
std::ostringstream ss;
ss << someStreamBuf;
std::string s = ss.str();
像,读一切从标准输入到一个字符串,执行
Like, to read everything from stdin into a string, do
std::ostringstream ss;
ss << std::cin.rdbuf();
std::string s = ss.str();
另外,您还可以使用 istreambuf_iterator
。你将不得不衡量这或以上的方式是更快的 - 我不知道
Alternatively, you may also use a istreambuf_iterator
. You will have to measure whether this or the above way is faster - i don't know.
std::string s((istreambuf_iterator<char>(someStreamBuf)),
istreambuf_iterator<char>());
注意 someStreamBuf
以上是为了重新present一个流缓冲*
,所以取它的地址适当。还要注意身边在最后一个例子,第一个参数的额外括号,所以它不跨preT它作为一个函数声明返回一个字符串,并考虑迭代器和另一个函数指针(最让人头疼的解析)。
Note that someStreamBuf
above is meant to represent a streambuf*
, so take its address as appropriate. Also note the additional parentheses around the first argument in the last example, so that it doesn't interpret it as a function declaration returning a string and taking an iterator and another function pointer ("most vexing parse").
这篇关于一个流缓冲的内容复制到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!