简体   繁体   中英

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?

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为您提供了无格式数据,ss.read为您提供了一个块,都是从istream 链接继承的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM