Rn2dy
Rn2dy

Reputation: 4190

Why cin.get(char *, int, char t) and cin.getline(char *, int, char t)?

The documentation says the cin.get(...) will leave the termination character(parameter t) in the buffer! I am wondering how could this be useful compared to getline(...) which will discard the termination character... BTW, suppose I have char buf[256], how can I flush that buf to cout?

Upvotes: 0

Views: 858

Answers (1)

Fred Nurk
Fred Nurk

Reputation: 14222

For lines, the terminating newline is considered part of the line, and you generally want to remove it when reading a line. Convention has determined that the resulting string containing the line not contain that newline, however, which is why getline discards it instead of storing it. (Other languages/libraries don't make the latter decision.)

For things other than lines, the delimiter may not be considered part of the field being extracted, so you want it to be left and later read.

suppose I have char buf[256], how can I flush that buf to cout?

If that's a C-string (terminated by a \0), then cout << buf;. Otherwise you can cout.write it as an unformatted sequence of bytes.

Upvotes: 2

Related Questions