Quuxplusone
Quuxplusone

Reputation: 27314

When should I `#include <ios>`, `#include <iomanip>`, etc.?

The C++ standard library provides the following headers related to iostreams:

<ios>
<iosfwd>
<istream>
<ostream>
<streambuf>
<iostream>
<fstream>
<sstream>
<strstream> [deprecated]
<iomanip>

What is the simplest, most sensible rule for when to #include which of these headers? (If the answer is different in different versions of C++, I'm most interested in C++17. And I'm most interested in what is guaranteed to work, not which headers happen to include other headers in libstdc++ or whatever.)

I would like to believe that I can always get by with <iostream>, <fstream> (only if I use fstreams), and/or <sstream> (only if I use stringstreams). This seems to work for simple programs like

#include <iostream>

int main() {
    std::cout << std::hex << 42 << std::endl << std::flush;
}

But if I add std::setw(42) to that program, then it stops compiling; I need to include <iomanip> as well in that case.

So the rule seems to be "include <iostream>, <fstream>, and/or <sstream>; and additionally include <iomanip> if you're using any of these manipulators."

If I follow this rule religiously, will I ever run into a case where I need to include <ios>, <iosfwd>, <istream>, <ostream>, and/or <streambuf> in my application code?

Upvotes: 3

Views: 6239

Answers (2)

Felix Dombek
Felix Dombek

Reputation: 14382

Will I ever run into a case where I need to include <ios>, <iosfwd>, <istream>, <ostream>, and/or <streambuf> in my application code?

Yes, you might:

<iosfwd> to save compilation time when you have a header which declares, but does not define, stream output operators for your types:

#include <iosfwd>
std::ostream& operator<<(std::ostream& os, const MyType& my);

<istream> and <ostream> in the cpp file which then defines such operators, again to save compilation time and keeping the scope clean over including <iostream>.

<ios> and <streambuf> probably only if you write a library which defines custom stream classes. Or maybe if you want to call sync_with_stdio() from some central settings class which does not actually do IO.

Upvotes: 0

Barry
Barry

Reputation: 303527

If I follow this rule religiously, will I ever run into a case where I need to include <ios>, <iosfwd>, <istream>, <ostream>, and/or <streambuf> in my application code?

Well, <iostream> includes <ios>, <streambuf>, <istream>, and <ostream>. And <iosfwd> are just forward declarations, so you don't really need that one either. So... I suppose, yes.

<fstream> gives you all the file-related stuff: filebuf, ifstream, ofstream, and fstream (and their wide counterparts).

<sstream> similarly gives you all the stringstream types and stringbuf.

All that leaves you with is remembering what's in <iomanip>, which isn't that much, but you could always just look it up.

Upvotes: 2

Related Questions