0

I'm confused about the use of #include <string> directive, I know it should be used before any string is included, also too the global function getline(), but how when do I build and execute the following program it doesn't gave back any errors when I not included #include <string> directive

#include <iostream>

using namespace std;

int main()
{

    string theName;

    cout << "Enter the name: ";

    getline(cin, theName);

    cout << "The name is " << theName << endl;


    return 0;
}
  • 5
    `` *happens* to be including string for you, but that's not the case for every compiler. The principle you want to learn is "Include what you use." So, you `#include ` if you're using strings. It's pretty straightforward. – sweenish Mar 11 '21 at 16:53
  • Depends on your compiler. `` may include `` already. See [here](https://stackoverflow.com/questions/59070255/how-to-determine-which-header-files-to-include) – ChrisMM Mar 11 '21 at 16:54
  • Probably it is already included in iostream. – Wais Kamal Mar 11 '21 at 16:54
  • 3
    `#include` statements are transitive - if header B includes header A and file C includes header B, the file C gets A as well. Standard library headers may include other headers, and this is what happens here. But it's generally a bad practice to rely on that behaviour - it makes your code very brittle. Someone may remove header A from includes in B, and suddenly file C stops compiling. Instead, always `#include` what your code uses. – Yksisarvinen Mar 11 '21 at 16:56

0 Answers0