[英]How to use std::cout or std::ofstream as an input of a single function?
我想实现以下目标:
#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::cout
构造std::ofstream
。
可行的解决方案是在上下文pointer_to_ofstream->basic_ios<char>::rdbuf(std::cout.rdbuf())
使用rdbuf()
pointer_to_ofstream->basic_ios<char>::rdbuf(std::cout.rdbuf())
(如本条目中所述)。
有更好的解决方案吗?
不要在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
块的第一个。
if (argc == 2){
std::ofstream outputStream(argv[1]);
write(outputStream);
}
else{
write(std::cout);
}
您已经得到了一个很好的答案。 这是另一种方法,它可能会回答您的第二个问题:
void write(std::ostream& o) {
o << "Some text..." << std::endl;
}
std::unique_ptr<std::ostream> stream( argc == 2
? std::make_unique<std::ofstream>(argv[1])
: std::make_unique<std::ostream>(std::cout.rdbuf())
);
write(*stream);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.