How can I read 2 characters from file into a std::string

S

SpreadTooThin

How can I read in two characters from a file into a std::string?

the long way:

fstream f("myfile.bin", ios::binary | ios:in); // Opened for read
binary...
unsigned char buffer[3];
buffer[2] = '\0';
f.read(buffer, 2);
std::string x(buffer);

Got a better way?
 
G

Gianni Mariani

SpreadTooThin said:
How can I read in two characters from a file into a std::string?

the long way:

fstream f("myfile.bin", ios::binary | ios:in); // Opened for read binary...
unsigned char buffer[3];
buffer[2] = '\0';
f.read(buffer, 2);
std::string x(buffer);

Got a better way?

fstream f("myfile.bin", ios::binary | ios:in);
char buffer[2];
f.read(buffer, 2);
std::string x(buffer, buffer+2);

They do behave differently.
 
J

James Kanze

How can I read in two characters from a file into a std::string?
the long way:
fstream f("myfile.bin", ios::binary | ios:in); // Opened for read
binary...
unsigned char buffer[3];
buffer[2] = '\0';
f.read(buffer, 2);
std::string x(buffer);
Got a better way?

std::string x ;
x += f.get() ;
x += f.get() ;

(Of course, you'll want to check that you actually did get two
characters.)

Something that will work with all current implementations, and
will be guaranteed by the next version of the standard:

std::string x( 2, ' ' ) ;
f.read( &x[ 0 ], 2 ) ;
 
G

Gianni Mariani

James Kanze wrote:
....
Something that will work with all current implementations, and
will be guaranteed by the next version of the standard:

Do you have a reference to the this proposal (contiguous strings)?
 
J

James Kanze

James Kanze wrote:
Do you have a reference to the this proposal (contiguous strings)?

It's in the current draft (N2134): "The char-like objects in a
basic_string object shall be stored contiguously. That is, for
any basic_string object s, the identity &*(s.begin() + n) ==
&*s.begin() + n shall hold for all values of n such that 0 <= n
< s.size()." From what I understand, a non-const version of
data() will also be added (as well as const and non-const data()
functions to std::vector), in order to obtain the address in a
way somewhat more transparently than &s[0].
 

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

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top