简体   繁体   中英

creating an iostream object in c++

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM