Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing to nowhere with ostream [duplicate]

I'd like to send data to nowhere, I mean that I don't want to print data in console nor in file, but I need some std::ostream object. How to do that?

like image 484
scdmb Avatar asked Oct 19 '11 08:10

scdmb


1 Answers

I've used:

std::ostream bitBucket(0);

recently without problems, although it was flagged as having some potential problems if you looked at it from a certain angle (see the link below).

Aside: From what I understand (and I'm not entirely sure of this), that call above eventually ends up calling basic_ios::init(0) and, because that's a NULL pointer being passed in, it sets the stream state, as returned by the rdstate() function, to the badbit value.

This in turn prevents the stream from outputting any more information, instead just tossing it away.

The following program shows it in action:

#include <iostream>

int main (void) {
    std::ostream bitBucket(0);
    bitBucket << "Hello, there!" << std::endl;
    return 0;
}

The page where I got it from also had this as a probably-cleaner solution (slightly modified to remove the duplication of my first solution above):

#include <iostream>

class null_out_buf : public std::streambuf {
    public:
        virtual std::streamsize xsputn (const char * s, std::streamsize n) {
            return n;
        }
        virtual int overflow (int c) {
            return 1;
        }
};

class null_out_stream : public std::ostream {
    public:
        null_out_stream() : std::ostream (&buf) {}
    private:
        null_out_buf buf;
};

null_out_stream cnul;       // My null stream.

int main (void) {
    std::cout << std::boolalpha;

    //testing nul

    std::cout << "Nul stream before: " << cnul.fail() << std::endl;
    cnul << "Goodbye World!" << std::endl;
    std::cout << "Nul stream after: " << cnul.fail() << std::endl;
}
like image 188
paxdiablo Avatar answered Nov 15 '22 21:11

paxdiablo