reading input from stringstream
I'm reading input to a char array of size 5,
stringstream ss;
char a[5];
if (!ss.read(a, 5))
{
// throw exception
}
if (!ss.get(a, 5))
{
// throw exception
}
Both of these functions seem to work, is there any di开发者_StackOverflowfference?
ss.read
will read 5 bytes from the stream, unless it hits the end of the stream.
ss.get
will read 4 bytes, unless it hits the delimiter ('\n') or end of the stream. It will also null-terminate the string.
The former will read 5 bytes, stopping early only upon encountering EOF.
The latter will read 4 bytes (allowing room for null-termination), stopping early upon encountering EOF or upon encountering '\n'
.
Which one you want depends on whether or not you intend for a
to behave semantically as a C-string.
http://www.cplusplus.com/reference/iostream/istream/read/ http://www.cplusplus.com/reference/iostream/istream/get/
Read is when you need blocks of data ( Ex: ss.read( a, 2 ) ) - This does not store it as a c-string and not null terminated.
Get - Extracts characters from the stream and stores them as a c-string into the array beginning at ss. Execution stops if there are delimiting characters like '\n' too.
ss.get gives you unformatyed data, ss.read gives you a block, both inherited from istream link
精彩评论