I am new to c++ programming, and based on what I learned we import the basic input and output functions from the <iostream> library. However, when I use the getline() function, which is used to take user's input with spaces: getline(cin, variable), the program works without including any other library, and I havent seen getline() in any references for the <iostream> header file.
Shouldn't there be a header file that we should include? Or, is it declared in <iostream> ?
I searched online but couldn't find any explanation to this.
1 Answer 1
Shouldn't there be a header file that we should include?
Yes - std::getline() is defined in the <string> header. See the documentation at cppreference.com:
Or, is it declared in
<iostream>?
Standard headers are allowed to include other standard headers, so in your particular compiler implementation, the <iostream> header is likely already including <string> for you, which is why your code compiles without needing #include <string> in your own code.
But, this is not guaranteed behavior, so you should not rely on it. Always explicitly #include any relevant header that your code needs. If a header has already been included earlier, your include of that header will simply be ignored as a no-op due to use of header guards.
4 Comments
<iostream> header file could have a #include <string> preprocessor directive in it. Or it may not. You don't know.#include <string> ?
<iostream>have no mention ofstd::getline(). With such a search, you would have easily turned up the information that Remy provided in his answer.