Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I call getline without using std::getline?

I am following the C++ Primer book and trying out all the code examples. I am intrigued by this one:

#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
    string line;
    while (getline(cin,line))
        cout << line << endl;
    return 0;
}

Before compiling this code I was guessing that the compilation would fail, since I am not using

while (std::getline(cin,line))

Why is getline in the global namespace? As I understand, this should only happen if I used

namespace std;

or

using std::getline;

I am using g++ version 4.8.2 on Linux Mint Debian Edition.

like image 663
Jose_mr Avatar asked Jul 23 '15 21:07

Jose_mr


People also ask

What can I use instead of Getline in C++?

Use the std::ws manipulator in the std::getline . Like: getline(cin >> ws, title); . This will eat potential leading whitespaces, including the newline.

Why Getline is not working?

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.

Why do we use Getline instead of CIN?

In C++, the cin object also allows input from the user, but not multi-word or multi-line input. That's where the getline() function comes in handy. The function continues accepting inputs and appending them to the string until it encounters a delimiting character.

Should I use getline or cin?

The main difference between getline and cin is that getline is a standard library function in the string header file while cin is an instance of istream class. In breif, getline is a function while cin is an object. Usually, the common practice is to use cin instead of getline.


2 Answers

This is argument dependent lookup.

Unqualified lookup (what you are doing when you just call getline() instead of std::getline()) will start by trying to do normal name lookup for getline. It will find nothing - you have no variables, functions, classes, etc. in scope with that name.

We will then look in the "associated namespaces" of each of the arguments. In this case, the arguments are cin and line, which have types std::istream and std::string respectively, so their associated namespaces are both std. We then redo lookup within namespace std for getline and find std::getline.

There are many more details, I encourage you to read the reference I cited. This process is additionally known as Koenig lookup.

like image 69
Barry Avatar answered Oct 14 '22 16:10

Barry


Since std::getline() for std::string is defined in the header I would have to say that Argument-dependent lookup is coming into play.

like image 7
NathanOliver Avatar answered Oct 14 '22 18:10

NathanOliver