使用 ostream 无处打印

Printing to nowhere with ostream(使用 ostream 无处打印)
本文介绍了使用 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 无处打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)