我想使用 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/