c++header-filesgetline

In what library or header file is the "getline()" function declared in?


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.


Solution

  • 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:

    image

    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.