使用 ostream 无处打印

2022-01-07 00:00:00 printing stream c++

我想将数据发送到任何地方,我的意思是我不想在控制台或文件中打印数据,但我需要一些 std::ostream 对象.怎么做?

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?

推荐答案

我用过:

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).

旁白:据我所知(我并不完全确定这一点),上面的调用最终会调用 basic_ios::init(0) 并且,因为这是传入的 NULL 指针,所以它会将 rdstate() 函数返回的流状态设置为 badbit 值.

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

相关文章