Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ' '. On the other hand, get() will just hangs the character in the input queue, thus potentially causing problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
521 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...