是否可以在C++中的文件中显示void函数cout输出



是否可以在文件中显示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<lt;"Hello World"<lt;endl;总的来说,它当然会在终端显示"你好世界"。现在,我不想在终端中显示它,而是想在text.txt文件中显示它。

限制:假设函数showhello()包含一千个cout输出,因此您不能使用以下内容:

fw << "Hello World" << endl;

或者复制粘贴到字符串中。它必须是fw<lt;作用

您可以按照以下方式重新定向:

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);

您可以引用流作为参数:

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';

我使用CCD_ 1而不是CCD_,因为CCD_ 3强制冲洗流
当您向控制台写入时,差异可能几乎不明显,但是当您写入磁盘时,
它强制立即访问磁盘,而不是等到有足够的数据以提高磁盘存储的效率。

最新更新