【问题标题】:Is it possible to show void function cout output in a file in C++?是否可以在 C++ 文件中显示 void 函数 cout 输出?
【发布时间】:2014-11-29 17:40:52
【问题描述】:

是否可以在文件上显示 cout 输出而不是在控制台/终端中显示?

#include <iostream>
#include <fstream>

void showhello()
{
    cout << "Hello World" << endl;
}

int main(int argc, const char** argv)
{
    ofstream fw;
    fw.open("text.txt");
    fw << showhello() << endl;
}

如果我简单地把 cout

限制: 假设函数 showhello() 包含一千个 cout 输出,所以你不能使用类似的东西:

fw << "Hello World" << endl;

或复制粘贴到字符串中。它必须是 fw

【问题讨论】:

标签: c++ file function void cout


【解决方案1】:

你可以做如下重定向:

std::streambuf *oldbuf = std::cout.rdbuf(); //save 
std::cout.rdbuf(fw.rdbuf()); 

showhello(); // Contents to cout will be written to text.txt

//reset back to standard input
std::cout.rdbuf(oldbuf);

【讨论】:

  • 确实有效。看到您只需将函数放在 streambuf 和 cout.rdbuf 之间,我有点惊讶。
【解决方案2】:

您可以将流的引用作为参数:

std::ostream& showhello(std::ostream& stream) {
    return stream << "Hello World";
}

//用法(我很惊讶它可以工作,谢谢@T.C.):

ofstream fw;
fw.open("text.txt");
std::cout << showhello << '\n';

//或者:

showhello(fw) << '\n';

我使用的是'\n' 而不是std::endl, 因为std::endl 强制刷新流。
当您写信给控制台时,差异可能几乎不明显, 但是当你写入磁盘时,
它强制立即访问磁盘, 而不是等到有足够的数据 以提高保存到磁盘的效率。

【讨论】:

  • 这很酷的一点是,如果你这样做,你实际上可以写fw &lt;&lt; showhello &lt;&lt; '\n'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
相关资源
最近更新 更多