1

I want to ask a question about reading C++ files.

I am a beginner in C++ and learning about file I/O.

I have the following txt file named poem.txt

Shall I compare thee to a summer's day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,
And summer's lease hath all too short a date:
Sometime too hot the eye of heaven shines,
And often is his gold complexion dimm'd;
And every fair from fair sometime declines,
By chance, or nature's changing course, untrimm'd;
But thy eternal summer shall not fade
Nor lose possession of that fair thou ow'st;
Nor shall Death brag thou wander'st in his shade,
When in eternal lines to time thou grow'st;
So long as men can breathe or eyes can see,
So long lives this, and this gives life to thee.

and the corresponding code:

#include <iostream>
#include <fstream>

int main () {
    std::ifstream in_file;
    in_file.open("poem.txt");
    if(!in_file) {
        std::cerr << "Problem opening file." << std::endl;
        return 1;
    }

    std::string line;

    while (std::getline(in_file, line)) {
        std::cout << line << std::endl;
    }

    in_file.close();
    return 0;
}

This code works. The poem is outputted as above in the terminal since we output each line in the while loop.

However, I have defined a variable of string type, std::string line but I have not included the #include <string> declaration, yet this code still works.

I've searched cppreference and there is no indication that <string> is also included in <iostream> or <fstream>.

So how am I able to print a string object to the standard output without <string> header declaration?

bodn19888
  • 167
  • 10
  • Yes, there is no requirement that `` will be included by `` or `` so you won't find that on cppreference. But those headers might include it anyway. – cigien Aug 23 '20 at 15:09

0 Answers0