Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iostream vs ostream what is different?

Tags:

c++

gcc

As the book says (Exploring C++: The Programmer's Introduction to C++):

The istream header declares input operators (>>), and ostream declares output operators(<<).

I can perfectly run the code without adding #include <ostream>:

#include <iostream>
using namespace std;
int main()
{
    cout << "hello world"<< endl;
    return 0;
}

But, in book's example like:

#include <iostream>
#include <ostream>    //why?
using namespace std;
int main()
{
    cout << "hello world"<< endl;
    return 0;
}

So, iostream, ostream and istream are header files right?

If ostream is not necessary (iostream does the job) why does the author include it in the example? Or why does the ostream header file still exist?

Note: In Bruce Eckel's Vol 1 book (which is published in 2000) there is nothing about ostream or istream. Only one header file which is iostream.

like image 619
Mustafa Ekici Avatar asked Feb 13 '12 19:02

Mustafa Ekici


People also ask

Does iostream include Ostream?

The iostream: This class is responsible for handling both input and output stream as both istream class and ostream class is inherited into it.

What is the difference between Ostream and istream?

istream is a general purpose input stream. cin is an example of an istream. ostream is a general purpose output stream. cout and cerr are both examples of ostreams.

What is Ostream in C++?

ostream class − The ostream class handles the output stream in c++ programming language. These output stream objects are used to write data as a sequence of characters on the screen. cout and puts handle the out streams in c++ programming language.

What are the different parts of iostream?

14.2 Basic Structure of iostream Interaction Standard input. Standard output. Standard error. A file.


1 Answers

As ildjarn noted in the comment, C++ standard from 2003 says that iostream does not necessary include istream and ostream. So, theoretically, the book is correct.

However, most major compiler vendors have added istream and ostream into iostream, so your code works on the compiler you are using. You might not have such luck on some other compiler.

If you want to write portable code that would compile on older compilers that only adhere to 2003 standard (or earlier), you should include both headers. OTOH, if you are the only one compiling your code and have control which compilers would be used, it's safe to use iostream only, because that is forward-compatible.

like image 131
Milan Babuškov Avatar answered Sep 21 '22 06:09

Milan Babuškov