One of my C++ books was showing the line cin.getline(arg, arg) and later showing getline(cin, arg). Why is the second one not object.function and yet have the object as one of the arguments? What's the difference?

Recommended Answers

All 2 Replies

Those two functions essentially do the same thing (read a line from cin). The difference between the two is that the member function (cin.getline(..)) takes an argument (the string to be filled in with the content of the line) as a char*, which is the C-style representation for strings (a pointer to an array of characters, terminated by a null-character), or "C-style string" for short. The non-member function version (getline(cin,..)) takes an argument as a std::string object (by reference), which is the standard (modern) C++ representation for strings.

The reason why the std::string version of getline is not a member function of the std::istream class (which is the class of cin) is for a historical reason. Basically, in the early days of C++, as people were designing the basic libraries that became the standard libraries, the IO stream libraries (to which std::istream belongs) were created before the string library was created (or made "standard"). Therefore, the getline function was a member of cin and relied on the more basic C-style string representation. When they created the C++ string library, they provided, as part of the string library (in the <string> header), a getline function to do the same as the other one, but with a std::string object instead of a char pointer.

Things were never changed after that, because there is no particular reason to change what's not broken. And it's not like it's easy to change things in the standard library of one of the most widely used language in the world.

Thanks mike, that answered my question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.