0

Why these two functions istream::get(char*, streamsize) and istream::get(char*, streamsize, char) set the cin.fail bit when they find '\n' as the first character in the cin buffer?

As can be seen here, that's the behavior of the two overloads mentioned above. I'd like to know what was the purpose in designing these functions this way ? Note that both functions leave the character '\n' in the buffer, but if you call any of them a second time, they will fail because of the newline character, as shown in the link. Wouldn't it make more sense to make these two functions not to leave the character '\n' in the buffer, as the overloads of the function istream::get() and istream::getline() do ?

Community
  • 1
  • 1
John Kalane
  • 1,163
  • 8
  • 17
  • Why `get` is not identical to `getline`, you ask? What would the point be? – n. m. could be an AI Jan 14 '13 at 17:47
  • You're right. By discarding '\n', get(char*, streamsize) would be equal to getline(). But again, what is the point of having a function like get() that leaves '\n' in the buffer and fails when called a second time? – John Kalane Jan 14 '13 at 17:53
  • The second version allows you to specify the delimiter, which can then be something other than `'\n'`. It is *you* who decide if you want to use the same delimiter twice (bad idea), not the library. – Bo Persson Jan 14 '13 at 18:21

1 Answers1

1

With std::istream::getline, if the delimiting character is found it is extracted and discarded. With std::istream::get the delimiting character remains in the stream.

With getline you don't know, if the delimiting character was read and discarded or if just n - 1 characters where read. If you only want to read whole lines, you can use get and then peek for the next character and see if it is a newline or the given delimiter.

But if you want to read whole lines up to some delimiter, you might also use std::getline, which reads the complete line in any case.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198