使用ostream到任何地方打印 [英] Printing to nowhere with ostream

查看:61
本文介绍了使用ostream到任何地方打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想无处发送数据,我的意思是我不想在控制台或文件中打印数据,但是我需要一些 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;
}

这篇关于使用ostream到任何地方打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆