#include <iostream>
#include <fstream>
int main() {
std::ofstream out("output.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); // 保存cout的缓冲区指针
std::cout.rdbuf(out.rdbuf()); // 重定向cout的输出到文件
std::cout << "This will be written to the file 'output.txt'" << std::endl;
std::cout.rdbuf(coutbuf); // 恢复cout的输出到控制台
std::cout << "This will be written to the console" << std::endl;
return 0;
}
在这个示例中,std::cout.rdbuf(out.rdbuf())将cout的输出重定向到文件,std::cout.rdbuf(coutbuf)将cout的输出恢复到控制台。