温馨提示×

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

c++
小樊
106
2024-08-13 00:42:38
栏目: 编程语言
C++开发者专用服务器限时活动,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的缓冲区切换回来,以确保之后的输出只会输出到标准输出。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C++ rdbuf与字符串流结合使用

0