Why is cin.getline inferior than getline?

I've read that cin.get() and cin.getline() are methods that work on C-strings and that getline(cin, variable) from std::string is better. Is there a reason not to use cin.get() or cin.getline() on C++ code? I understand that cin.getline() works on char arrays, but is that the only difference?
closed account (E0p9LyTq)
std::getline() requires you specify what the input stream is used, whether std::cin or a file.

std::cin.getline() is tied to one input stream, cin.

The problem really is not with the functions like cin.get(), cin.getline() the problem is really using C-strings. The std::string class is considered by many/most to be far superior to C-strings.

First std::string is dynamic and the class knows the length of the string. C-strings sizes are fixed at compile time and are vulnerable to buffer overrun errors if used improperly.

Just as @jlb said: these function does different things. Problem with cin.getline lies with usage of c-strings which should be raryely used in C++ code.

std::cin.getline() is tied to one input stream, cin.

Actually remember this is std::istream::getline(char*, streamsize), so it can be used with any input stream, not just cin, the same with getline(std::istream&, std::string&).
closed account (E0p9LyTq)
@jlb,

You are correct, but the OP was talking about cin.get()/cin.getline(). A specialization of std::istream::getline().

And I had forgotten about istream::getline(), ooops! ;)
Last edited on
Thanks everyone for all the great info you provided :)
But let's say I am not using C-style char arrays and all my strings are of type std::string instead, and my input stream is always cin (to read from keyboard).
In that case, is there any disadvantage from using cin.get or cin.getline to read keyboard input within C++?
If you're talking about strings and you're not using C-strings then you should prefer getline(std::istream&, std::string) to get a string since get() is not overloaded for a std::string.

And note getline() or get() works with any input stream, you're not limited to just using std::cin.



all my strings are of type std::string
cin.getline
You cannot pass std::string to cin.getline. You can pass a pointer to first character, but results will not be those you are expecting.
Topic archived. No new replies allowed.