C ++如何创建一个函数,该函数在终端和文件上打印
c++ how to create a function, that prints on terminal as well as file
我想创建一个函数,根据其参数打印输出。
就像如果我传递一个 ofstream 指针,它应该将输出打印到相应的文件,而如果我传递 cout 或其他东西,它会打印到终端。
谢谢:)
void display(std::ostream& stream)
{
stream << "Hello, World!";
}
...
display(cout);
std::ofstream fout("test.txt");
display(fout);
template<typename CharT, typename TraitsT>
void print(std::basic_ostream<CharT, TraitsT>& os)
{
// write to os
}
这将允许写入任何流(窄或宽,允许自定义特征)。
这应该可以做到:
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
相关文章:
- 如何使用重新定义的打印函数打印Lua表?
- 从函数打印 CLI 帮助消息后,我应该如何干净地退出 C++ 程序?
- 使用成员函数打印对象
- 函数打印输出C 的错误
- 函数打印奇怪的值.C++
- Std::copy 和 std::ostream_iterator 使用重载函数打印值
- C++ 通过函数打印出 2D 数组
- 使用模板函数打印智能指针矢量
- C 是否可以使用宏从称呼的地方进行类函数打印
- infix/postfix/prefix程序.想要使用我的printresult()函数打印结果.需要帮助获得输出
- 从 Main 中的双指针函数打印出指针数组
- 如何使用递归函数打印节点树
- 重载函数打印
- 尝试通过函数打印时"Garbage" 2D 数组中的值
- 如何通过包含要打印的字符串的类函数打印异常
- 从函数C++打印出 2D 数组
- 如何通过wprintf函数打印uint32_t变量值
- 为什么我的函数打印地址而不是数组的内容
- 为什么这个函数打印的是x而不是1
- 将函数打印到输出文件