Binary vs. formatted std::string reading/writing to streams

L

Leslaw Bieniasz

Hi,

I need to write and read std::strings as whole objects
from/to std::streams, either in a formatted or binary way.
Are there any built-in mechanisms for doing this (any global
functions or class methods in std::string)?
I cannot find any.

Formatted writing seems easy, for example:

std::eek:stream outstr;
std::string str;
outstr << str;

outputs entire str to outstr. However, something like

std::instream instr;
std::string str;
instr >> str;

gets only the first continuous sub-string contained in
instr into str. The sub-string may not be identical to
the entire string that was earlier written to the stream
from which the reading is performed.

What I need is a possibility to save an std::string into a stream/file
and then re-read the entire string from the same stream/file,
even if the string contained separate sub-strings.
Perhaps some sort of binary reading/writing can be applied?

A related question is:

Is this legal to open streams in binary mode, and use operators
<< and >> to read or write from these streams? For example,
if I open a binary stream, can I save (and later correctly retrieve)
some objects in it using binary writing, and some other objects using
formatted writing employing operators << and >> ?

Leslaw
 
T

Thomas J. Gritzan

Am 15.01.2010 11:42, schrieb Leslaw Bieniasz:
I need to write and read std::strings as whole objects
from/to std::streams, either in a formatted or binary way.
Are there any built-in mechanisms for doing this (any global
functions or class methods in std::string)?
I cannot find any.

Formatted writing seems easy, for example:

std::eek:stream outstr;
std::string str;
outstr << str;

outputs entire str to outstr. However, something like

std::instream instr;
std::string str;
instr >> str;

gets only the first continuous sub-string contained in
instr into str.

nistr >> str; stop reads until it finds a whitespace.

If you want to read a line of text, use std::getline:

std::getline(instr, str);

This function reads until it find a '\n' character in the stream. For
another delimiter, there's also a three argument version of that
function where the third parameter is the delimiter:
http://www.cplusplus.com/reference/string/getline/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top