Why are there two different getline() functions (if indeed there are)?

paxdiablo picture paxdiablo · Feb 2, 2011 · Viewed 17.6k times · Source

Every time I do a quick snippet of C++ code line

std::string s;
cin >> s;

I curse myself because I forgot it stops at the whitespace rather than getting an entire line.

Then, on remembering getline, I invariably become confused as to the two varieties:

std::string s;
getline (std::cin, s);

and:

char cs[256];
std::cin.getline (cs, sizeof (cs));

Is there actually a difference between these two other than the data type?

It seems to me the C++ way should be the former. Under what circumstances would I use the latter, given that I probably should be using real strings instead of null-terminated character arrays anyway?

And, since input should really be the purview of the input streams, why isn't the former part of istream?

Answer

Frédéric Hamidi picture Frédéric Hamidi · Feb 2, 2011

The global getline() function works with C++ std::string objects.

The istream::getline() methods work with "classic" C strings (pointers to char).