Conversion from std::string to char *, is there a better way?

J

Julie

Julie said:
I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

// presume s from somewhere, such as:
std::string s = "<initial value>";

std::vector<char> v(s.length() + 1);
std::strcpy(&v[0], s.c_str());
char * c = &v[0];
// use c, where a char * is _specifically_ required
s = c;

So then, under the presumption that this is about as 'clean' as it can get,
does anyone have a comment on why a method for direct access wasn't provided in
the std::string implementation? I'd have presumed that something like that
would have been requisite to be more compatible w/ C and C-style strings and
interfaces.

Something like:

class string
{
private:
char * _accessbuf; // NULL initialized in constructor
public:

char * string::access(const size_t num_chars)
{
delete [] _accessbuf;
_accessbuf = new char[num_chars+1];
copy(_accessbuf, num_chars, 0);
_accessbuf[num_chars] = '\0';
return _accessbuf;
}

void string::commit(const bool commit=true)
{
if (_accessbuf)
{
if (commit)
{
*this = _accessbuf;
}
delete [] _accessbuf;
_accessbuf = NULL;
}
}
// etc.
};

Then, accessing C-style interfaces would resolve to:

GetFileName(str.access(_MAX_PATH), _MAX_PATH);
str.commit();

instead of the cumbersome method in my original post.

Comments?

(Note: the names access and commit are completely arbitrary, more appropriate
names probably exist.)
 
C

Chris Gordon-Smith

Maybe I misunderstood your post, by I find string::c_str() works well for
me.
 
J

Julie

Chris said:
Maybe I misunderstood your post, by I find string::c_str() works well for
me.

c_str() returns a const pointer, so you can't directly modify the contents.

My proposal is for something that would encapsulate my original code into two
methods that would return a non-const pointer so that the contents can be
directly modified.
 
O

Owen Jacobson

c_str() returns a const pointer, so you can't directly modify the contents.

My proposal is for something that would encapsulate my original code into two
methods that would return a non-const pointer so that the contents can be
directly modified.

Why, exactly, do you want to do this?
 

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
474,173
Messages
2,570,938
Members
47,473
Latest member
pioneertraining

Latest Threads

Top