我正在尝试下面的代码片段,但它没有给出所需的输出:
#include<iostream>
#include<sstream>
using namespace std;
void MyPrint(ostream& stream)
{
cout<<stream.rdbuf()<< endl;
}
int main()
{
stringstream ss;
ss<<"hello there";
MyPrint(ss); //Prints fine
ostringstream oss;
oss<<"hello there";
MyPrint(oss); //Does not print anything
getchar();
}我知道stringstream和ostringstream之间唯一可能的区别是后者迫使方向,并且比stringstream快一点。
我错过了什么吗?
PS:早些时候也有类似的问题,但没有得到任何答案。
发布于 2013-08-15 19:06:04
std::stringstream和std::ostringstream向std::stringbuf传递不同的标志。特别是,std::ostringstream的std::stringbuf不支持读取。std::cout << stream.rdbuf()是streambuf上的读操作。
从std::ostringstream中提取字符的方法是使用std::ostringstream::str()函数。
发布于 2013-08-15 19:10:38
stringstream不应该被认为是ostringstream和stringstream的双向实现。它是作为一个派生的类实现的,这就是为什么它同时实现了输入和输出功能。
选择使用哪一个取决于它的用途。如果您只需要在流上写入数据,而不能通过流访问数据,那么您所需要的就是ostringstream。然而,如果你想在你提供给API的东西上实现双向,但是限制它,你可以强制转换它:
stringstream ss; // My bidirectional stream
ostringstream *p_os = &ss; // Now an output stream to be passed to something only allowed to write to it.
int bytes = collectSomeData(p_oss);https://stackoverflow.com/questions/18251346
复制相似问题