0
votes

I'm not fluent in C++, so I'm sorry that this is such a simple question. I'm working on a school assignment and in one of the questions, it asks us to write a function with the following prototype

    void function_name(istream &in, ostream &out, other arguments);

I don't really know what the first two arguments mean. From what I know, and correct me if I'm wrong. An istream is a class that is used in input. cin is an object of this class. An ostream is a class that is used in output. cout and cerr are objects of this class. objects of the istream class have methods such as fail() and .eof() to detect errors during input. Objects of the ostream class have methods such as .width() and .precision() to help format the output.

So from what I understand in the question, the first two arguments must be pointers to istream and ostream objects. Can anyone give me an example of a function that takes istream and ostream object pointers as arguments so that I can understand how to use them in my question?

Sorry if this is too long. Thanks for the help.

3
They are not pointers (*), they are references (&). - Colin Basnett
Damn. I always get these two confused. Is there a difference in this case? - Many Questions
The important distinction is that a pointer can be null, while a reference is "guaranteed" (sort of) to be a valid object. The calling convention is also different for pointers. There are plenty of resources like this one (programmers.stackexchange.com/questions/195337/…) that can explain it in detail. Highly recommended to understand the differences. - Colin Basnett

3 Answers

4
votes

the first two arguments must be pointers to istream and ostream objects

That is a misunderstanding. Those arguments are reference arguments, not pointers.

Example:

void foo(istream &in, ostream &out, int& x)
{
    in >> x;
    out << x;
}

int main()
{
   int x;

   // Read x from stdin and write to stdout
   foo(std::cin, std::cout, x);

   std::ifstream ifile("input.txt");
   std::ofstream ofile("output.txt");

   // Read x from input.txt and write to output.txt
   foo(ifile, ofile, x);
}
2
votes

1st thing, those are actually references, not pointers. 2nd thing, you use in and out just like you would use std::cin and std::cout. But when you call the function, you can specify different streams the function will use. For example if you want the function to write to file "test.txt" instead of the console, you declare std::ofstream ofs ("test.txt", std::ofstream::out);, which you then pass to the function.

Also, when working with streams, don't forget to close them when you're done with them.

1
votes

Those are references, not pointers. Google the difference.

As for your main question. You can treat them exactly as you treat cin and cout for reading/writing from/to standard input, respectively. That is, using << and >>.