c++ cout如何与其他输出流结合使用

avatar
作者
筋斗云
阅读量:0

在C++中,可以使用std::cout结合std::ofstream来将输出内容同时输出到标准输出和文件中。

例如,可以这样写:

#include <iostream> #include <fstream>  int main() {     std::ofstream file("output.txt");          std::streambuf *coutbuf = std::cout.rdbuf(); // save old buf     std::cout.rdbuf(file.rdbuf()); // redirect std::cout to output.txt          std::cout << "This will be output to both the console and the file." << std::endl;          std::cout.rdbuf(coutbuf); // restore old buf          std::cout << "This will only be output to the console." << std::endl;          file.close();          return 0; } 

在这个例子中,将std::cout的缓冲区切换到file对象的缓冲区,这样输出的内容将同时输出到标准输出和文件output.txt中。最后,记得要将std::cout的缓冲区切换回来,以确保之后的输出只会输出到标准输出。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!