c ++如何创建一个在终端和文件上打印的函数

时间:2012-05-04 17:34:32

标签: c++ function parameter-passing

我想创建一个函数,根据参数打印输出 就像我传递一个流指针一样,它应该将输出打印到相应的文件,而如果我传递cout或其他东西,那么它会打印到终端。

谢谢:)

3 个答案:

答案 0 :(得分:3)

void display(std::ostream& stream)
{
    stream << "Hello, World!";
}

...

display(cout);

std::ofstream fout("test.txt");
display(fout);

答案 1 :(得分:2)

template<typename CharT, typename TraitsT>
void print(std::basic_ostream<CharT, TraitsT>& os)
{
    // write to os
}

这将允许写入任何流(窄或宽,允许自定义特征)。

答案 2 :(得分:1)

这应该这样做:

template<class T>
std::ostream &output_something(std::ostream &out_stream, const T &value) {
    return out_stream << value;
}

然后你会像这样使用它:

ofstream out_file("some_file");
output_something(out_file, "bleh");  // prints to "some_file"
output_something(std::cout, "bleh"); // prints to stdout