I am new to programming, and I have some questions on get()
and getline()
functions in C++.
My understanding for the two functions:
The getline()
function reads a whole line, and using the newline character transmitted by the Enter key to mark the end of input. The get()
function is much like getline()
but rather than read and discard the newline character, get()
leaves that character in the input queue.
The book(C++ Primer Plus) that I am reading is suggesting using get()
over getline()
. My confusion is that isn't getline()
safer than get()
since it makes sure to end line with '\n'
. On the other hand, get()
will just hangs the character in the input queue, thus potentially causing problem?
There are an equivalent number of advantages and drawbacks, and -essentially- all depends on what you are reading: get()
leaves the delimiter in the queue thus letting you able to consider it as part of the next input. getline()
discards it, so the next input will be just after it.
If you are talking about the newline character from a console input,it makes perfectly sense to discard it, but if we consider an input from a file, you can use as "delimiter" the beginning of the next field.
What is "good" or "safe" to do, depends on what you are doing.