c++ - 如何传递 ostream 并使用 cout 在函数中显示在屏幕上?

标签 c++

我想使用 istream 和 ostream 作为我的函数采用的参数并帮助我完成工作(读取文件并在屏幕上显示内容)。 我知道如何使用 istream 做到这一点:

std::ifstream myfile(...);

void foo(myfile);

void readFoo(std::istream &stream)
{
  int x, y;
  stream >> x >> y;  //suppose my file contains many rows of 2 numbers.
  //store the x and y to somewhere 
}

void writeFoo(std::ostream &output)
{
???
}

我应该将什么对象传递给我的 writeFoo()?

更新: 这是更新,但我收到一条错误消息(无法从 ostream 转换为 ostream*)

writeFoo(std::cout);
writeFoo(sd::ostream &out)
{
  out << somedata to display to the screen;
}

最佳答案

您可以传递派生自 std::ostream任何输出流

例如:

writeFoo(std::cout);  //write to stdout

std::ofstream file("output.txt"); //open/create a file first
writeFoo(file);       //write to output.txt

希望对您有所帮助。

关于c++ - 如何传递 ostream 并使用 cout 在函数中显示在屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753169/

相关文章:

c++ - 如何将ifstream&从方法返回分配给变量?

c++ - 将单元格分配给 3 x 3 网格中的坐标

c++ - std::string 中的内存泄漏

c++ - 我应该使用什么类型的容器来存储我的 ObjectID 整数?

c++ - 超过 2 维的多维数组看起来如何?

c++ - 使用 GCC 或 Clang 编译 Microsoft Visual Studio Windows 库

c++ - 如何使用 C++ 将 wxImage 存储到数据库中?

c++ - 如何在不递归的情况下删除链表?

c++ - 为什么 std::bind 不考虑功能元数?

c++ - “数据”未在此范围内声明