creating an iostream object in c++

守給你的承諾、 提交于 2019-12-24 11:50:11

问题


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.

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.

based on what I've read, here is what I tried:

#include <iostream>


using namespace std;

int main(){
    streambuf* sb;
    iostream s(sb);

    s.put('h'); //segfault
}

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));
}

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.

If iostream is the wrong way to do this, please let me know of a better option.


回答1:


stringstream is exactly what you want. C++ strings can contain embedded null characters (\0). If you don't believe me, try it.

iostream is really an abstract base class and has no real functionality on its own. You should not be creating instances of iostream directly.



来源:https://stackoverflow.com/questions/14142649/creating-an-iostream-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!