The difference between cin.get () and cin.getline ()

I am new to programming and I have some questions about the get() and getline() functions in C ++.

My understanding of two functions:

The getline() function reads an entire line and uses the newline character passed by the Enter key to mark the end of the input. The get() function is very similar to getline() , but instead of reading and discarding a newline, get() leaves that character in the input queue.

The book (C ++ Primer Plus) that I am reading suggests using get() over getline() . My confusion is that it is not getline() safer than get() , since it terminates the line with '\n' . On the other hand, get() will just hang a character in the input queue, which can cause problems?

+5
source share
3 answers

There are an equivalent number of advantages and disadvantages, and also - necessarily - it all depends on what you read: get() leaves the delimiter in the queue, which allows you to consider it as part of the next input. getline() discards it, so the next input will be right after it.

If you are talking about a newline character from the console input, it makes sense to cancel it, but if we look at the input from a file, you can use the beginning of the next field as a "separator".

What is “good” or “safe” to do depends on what you do.

+10
source

get() extracts char from char from a stream and returns its value (cast as an integer), while getline() used to get a line from a file line by line. Typically, getline is used to filter separators in applications where you have a flat file (with thousands of lines) and you want to extract the result (in turn) using a specific separator and then perform some operation on it.

+6
source

cin.get () accepts the input of the entire line, which includes the end of the line, repeating it will consume the next whole line, but getline () is used to get line from line to line.

0
source

Source: https://habr.com/ru/post/1206668/


All Articles