parc65
parc65

Reputation: 191

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

Upvotes: 3

Views: 4768

Answers (4)

Nikiton
Nikiton

Reputation: 278

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

Upvotes: 1

Tim
Tim

Reputation: 9172

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.

Upvotes: 7

Raja
Raja

Reputation: 442

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.

Upvotes: 3

ildjarn
ildjarn

Reputation: 62975

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.

Upvotes: 3

Related Questions