我想实现这样的目标:
#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/