3

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 difference?

0

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

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.

Comments

1

ss.get gives you unformatyed data, ss.read gives you a block, both inherited from istream link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.