c++ - 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?

标签 c++

我想实现这样的目标:

#include <iostream>
#include <fstream>
#include <string>

void write(std::ofstream& o)
{
    o << "Some text..." << std::endl;
}

int main(const int argc, const char** argv)
{
    if (argc == 2){
        auto outputStream = std::ofstream(argv[1]);
        write(outputStream);
    }
    else{
        auto outputStream = std::ofstream(std::cout);
        write();
    }
}

代码无法编译,因为 std::ofstream不能从 std::cout 构造.

一个可行的解决方案是使用 rdbuf()在上下文中pointer_to_ofstream->basic_ios<char>::rdbuf(std::cout.rdbuf()) (在 this 条目中提供)。

有没有更好的解决方案?

最佳答案

不要在write 中使用std::ofstream。使用 std::ostream

void write(std::ostream& o)
{
    o << "Some text..." << std::endl;
}

此外,

 auto outputStream = std::ofstream(std::cout);
 write();

是不对的。只需使用。

 write(std::cout);

我也会更改 if block 的第一个。

if (argc == 2){
    std::ofstream outputStream(argv[1]);
    write(outputStream);
}
else{
    write(std::cout);
}

关于c++ - 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57466032/

相关文章:

c++ - 为什么 sizeof int 是错误的,而 sizeof(int) 是正确的?

c++ - 错误 : no match for ‘operator=’

C++/Qt - 可选参数默认为 NULL

c++ - 这个 C++ 声明是什么意思?

c++ - 对 `sd_notify' 的 undefined reference

c++ - 代码块抛出有关 for_each 的预期主表达式错误

c++ - C++ 中的全局变量

c++ - 查找 n 个数组中的唯一元素

c++ - 打包应用程序是否比 C++ 更适合创建跨平台串行读/写应用程序以与我的 mbed 电子项目通信?

c++ - 如何在 C++ 中获取类型的大小?