Printing to nowhere with 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 therdstate()
function, to thebadbit
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 无处打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ostream 无处打印
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01