Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ getline() doesn't require namespace declaration

Tags:

c++

scope

Why is getline() from header string in local scope and can be used:

#include <iostream>
#include <string>

int main() {
    std::string str;
    getline(std::cin, str);
    std::cout << str << "\n";
    return 0;
}

That works with gcc. But why? It is defined in header string, which should required me to use std::getline() instead of getline().

like image 389
Peter Avatar asked Apr 13 '13 18:04

Peter


People also ask

Why CIN Getline is not working in C++?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

Does Getline take whitespace?

The getline function reads in an entire line including all leading and trailing whitespace up to the point where return is entered by the user.

What does getline () do in C++?

The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input.

What library is needed for Getline in C++?

C++ has many libraries in its general standard library. Three of the libraries involved with getline are the iostream library, the string library, and the fstream library. The iostream library is typically used for input from the keyboard and output to the console (terminal).


1 Answers

You're experiencing Argument Dependent Lookup (ADL, and also referred to as Koenig Lookup). Since one or more of the arguments is a type defined in the std namespace, it searches for the function in the std namespace in addition to wherever else it would search. I point you to Stephan T. Lavavej's video to learn more about it and name lookup in general.

like image 181
chris Avatar answered Sep 18 '22 00:09

chris