问题描述
我要再试一次,但要比上次更好。
I'm going to try asking this again, but better than the last time.
我有一个程序从不同的地方读取二进制数据,然后在我写的类中操作它。数据将最初从其源代码读取(可能不同),然后写入流,该流将传递到类中以供工作。
I have a program that reads binary data in from various places, and then manipulates it in a class that I have written. The data will be read originally from it's source (which may vary), then get written to a stream, and that stream will be passed into the class for the class to work on.
我的努力是找出如何创建一个 iostream
并写入/读取。我已在各个地方查看,并阅读了的参考资料,但我可以找到一个简单的例子,说明如何创建一个 iostream
。
My struggles are with figuring out how to create an iostream
and write to/read from it. I have looked in various places and read the references at cplusplus.com, but I can't find a simple example of how to create an iostream
.
是我试过的:
#include <iostream>
using namespace std;
int main(){
streambuf* sb;
iostream s(sb);
s.put('h'); //segfault
}
坦率地说,我不知道为什么会出现segfaulting,修复它,所以我要求有人告诉我如何正确创建一个 iostream
对象,最终,我将能够执行类似以下内容:
Frankly, I have no idea why its segfaulting, or how to fix it, so I am asking for someone to tell me how to properly create an iostream
object that, ultimately, I will be able to execute something like the following on:
void printByN(iostream s, n){
while (s.peek() != eof()){ // I'm not sure this is correct. need help with that too
char buf [n];
s.read(&buf, n);
cout << buf << endl;
}
}
int main(){
//create iostream s;
char* buf = "hello there my friend";
s.write(buf, strlen(buf));
}
关键是我需要流知道它是空的,一个特殊的值。我不能使用 stringstream
,因为二进制数据可能包含不意味着终止数据的空字符。
The point is I need the stream to know when it is empty, and return a special value at that point. I cannot use a stringstream
, because it is possible for the binary data to contain null characters that ARE NOT meant to terminate the data.
如果 iostream
是错误的方法,请让我知道更好的选择。
If iostream
is the wrong way to do this, please let me know of a better option.
推荐答案
stringstream
正是你想要的。 C ++字符串可以包含嵌入的空字符( \0
)。如果您不相信我,请。
stringstream
is exactly what you want. C++ strings can contain embedded null characters (\0
). If you don't believe me, try it.
iostream
实际上是一个抽象的基类,没有真正的功能。您不应直接创建 iostream
的实例。
iostream
is really an abstract base class and has no real functionality on its own. You should not be creating instances of iostream
directly.
这篇关于在c ++中创建一个iostream对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!