Debugging ofstream.(C++)
Debugging ofstream.(C++)
我需要创建一个流调试,它具有如下功能:
#define DEBUG true
int main() {
debug << "Hello Worldn";
}
上述情况下的输出应为:Hello World
对于以下代码-
#define DEBUG false
int main() {
debug << "Hello Worldn";
}
输出应为空。任何建议我应该如何进行。
根据您的使用,我认为debug
需要宏,因为没有其他方法可以获取DEBUG
的值。一个简单的定义是这样的:
#define debug (debugstream << enable<DEBUG>)
extern std::ostream debugstream;
template <bool Enable>
std::ostream& enable(std::ostream& out) {
if (Enable) {
out.clear();
}
else {
out.setstate(std::ios_base::badbit);
}
return out;
}
std::ostream debugstream(std::cout.rdbuf()); // probably defined in a separate translation unit
这里的诀窍是使用流的启动启用/禁用输出的打印:当流处于良好状态时,即如果设置了std::ios_base::failbit
或std::ios_base::badbit
,则不会生成任何输出(由正确写入的输出运算符(。可以通过设置/取消设置流缓冲区来强制使用此行为,而不是使用 rdbuf()
。
正如我从您的问题中了解到的那样,您希望有一个单独的调试流(与 std::cout
和 std:cerr
相反(。你可以通过制作一个"空流"来实现这一点,它只是吃掉所有东西而不做任何事情。
如果你的编译器足够聪明,那么它甚至应该最终删除大部分内容。
class NullStream {};
template<typename T>
NullStream& operator<<(NullStream& s, T const &) { return s; }
NullStream& operator<<(NullStream& s, std::ostream&(std::ostream&)) { return s; }
现在,根据您的宏,您可以决定是使用NullStream
还是实际ostringstream
。
#if DEBUG
std::ostringstream debug;
#else
NullStream debug;
#endif
像这样测试它:
debug << "Hello Worldn";
debug << 12345 << "n";
debug << "Test" << std::endl;
#if DEBUG
std::cout << "Debug:" << std::endl;
std::cout << debug.str() << std::endl;
#endif
如果不0
DEBUG
,则会产生:
调试:
世界您好
12345
测试
请注意,NullStream
本身没有任何std::ostream
的功能,因此另一种解决方案可能是从std::ostream
派生并丢弃它收到的任何输入。
相关文章:
- std::ofstream 作为类成员删除复制构造函数?
- ofstream::close() 是否在 Linux 上调用同步?
- 如何在软件代码中使用ofstream创建文件
- Ofstream和IFSTREAM有什么区别?
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- fstream / ifstream / ofstream 对象如何转换为布尔值
- 使用 auto_ptr<std::ofstream> 对象
- 传递数组结构、ofstream 和 interger 以运行
- 有没有办法使用 ofstream 保存屏幕截图?
- 使用 ofstream 写入文本文件时断言失败
- 当 ofstream 指针位于 std::map 中时,文件写入不会发生 C++.
- Ofstream一直给我函数的最后一行,而不是显示所有内容
- 如何将 std::ofstream& 传递给函数参数?
- BigInteger:在 C++ 中使用 ofstream 写入文件时如何将基数更改为 2?
- 数据不是用 ofstream 写入的,即使返回成功也是如此
- ofstream将额外的零字节写入Unix服务器上的文件
- 为什么我不能将 Windows 环境路径与 ofstream 一起使用来编写文本文件?
- 为什么 ofstream 比 fprintf 慢?
- 派生 std::ofstream 和重载运算符<<