ABC
ABC

Reputation: 2148

When to include the <string> header in your program?

Do you include the "string" header when a library such as "iostream" already provides a solution?

Example: Do you include the string library if you have already included the iostream library? Which is the right professional method?

#include <iostream>
#include <fstream>

using namespace std;
int main() {
    ifstream fin;
    fin.open("input.txt");
    string data;
    fin >> data;
    cout << data << endl; // Works with <iostream>, and without <string>
    fin.close();
    return 0;
}

Example 2: Use string library if another library provides functionality, even if program compiles without string?

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main() {
    ifstream fin;
    fin.open("input.txt");
    string data;
    fin >> data;       
    cout << data << endl; // Even though <iostream> allowed program to compile, we include the <string> library.
    fin.close();
    return 0;
}

Received points off my CSC 101 class programming assignment because even though program worked, teacher said when using the string datatype I needed to include the string library. Even though technically it was fine without it possibly. Thats the question.

Upvotes: 2

Views: 168

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Your teacher was correct.

Your program worked without <string> by chance. Your standard library implementation, of that version, on that platform, under those circumstances, on that day, transitively included what you needed via <iostream>. The standard library is just code, like yours, and it just so happens that your particular implementation contains, inside <iostream>, an #include <string>. It could be buried behind many other #includes but got there eventually. But that's honestly pure chance, and does not mean that this is something the language guarantees, or something that must always be the case even in practice.

You should always code to standards.

If you're using features from <string>, include <string>.

Just today I was trying to build my big project with a new toolchain and found a few places where I'd accidentally relied on transitive includes, and it broke the build as a result because the new standard library implementation had a slightly different arrangement of headers. I dutifully added the missing #includes and now the world is a better place for it.

Upvotes: 4

Related Questions