Topic: Does the standard guarantee that the elements of string be contiguous in memory after calling the method string::c_str() or string::data() ?
Author: "Laurent Laporte" <informatique@pedagofiche.fr>
Date: Fri, 23 Mar 2001 20:42:17 GMT Raw View
Anon Sricharoenchai <ans@beethoven.cpe.ku.ac.th> a crit dans le message :
3AB6577D.9CA9CEC4@naist.cpe.ku.ac.th...
: Does the standard guarantee that the elements of string be contiguous in
: memory after calling the method string::c_str() or string::data() ?
That's not a complete answer : it depends of the default memory allocator of
basic_string for char type.
: If not, I think it should.
I do too.
: This will very useful when I want to pass string as nonconst char* into
: C-style function, for example,
: to read data from a file descriptor in unix,
:
: string str; str.resize(20); str.data();
Why do you call data() without using it's retrun value? It's a type error,
isn't it?
Instead of:
string str; str.resize(20);
you ca write:
string str(20, '\0');
in order to reserve a 20 characters space.
: read(fd, &str[0], str.length());
:
: that will be more efficient than,
:
: string str; vector<char> buf(20);
: read(fd, &buf[0], buf.length());
: str.assign(&buf[0], buf.length());
You can use an ostringstream in conjonction with your ifstream:
ifstream in(your_file);
ostringstream out;
out << in.rdbuf();
out.str() returns a string (the copy of the file into a string).
------- Laurent.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html ]