-1

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.

asked Nov 14, 2024 at 21:42
1
  • You could have readily found an answer to this question for yourself by searching for "C++ getline" after finding that documentation for <iostream> have no mention of std::getline(). With such a search, you would have easily turned up the information that Remy provided in his answer. Commented Nov 15, 2024 at 3:14

1 Answer 1

6

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.

answered Nov 14, 2024 at 21:43
Sign up to request clarification or add additional context in comments.

4 Comments

"Standard headers are allowed to include each other," what do you exactly mean by this?
@MohamadKhalil • it means the <iostream> header file could have a #include <string> preprocessor directive in it. Or it may not. You don't know.
So what could be the reason if it didn't have #include <string> ?
A good reference always helps, look at the 1st line under the title std::getline - cppreference.com

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.