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.
Use the std::ws manipulator in the std::getline . Like: getline(cin >> ws, title); . This will eat potential leading whitespaces, including the newline.
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.
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.
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.
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.
Since std::getline()
for std::string
is defined in the header I would have to say that Argument-dependent lookup is coming into play.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With