Skip to main content
gamedev.net
🔒 Locked

stringstream - char* ?

Started by Majirok Jan 22, 2006 at 8:49 PM 2 replies 5.9k views
Original Post
Majirok
Majirok
I'm using an older C function in C++ (my first mistake, I know :P). The first parameter requires a pointer to a character array, and I was just wondering whether I could use a stringstream or even a string rather than a raw character array to do the job. The problem is that ss.str().c_str() returns a const pointer. The same with s.c_str(). The function is expecting a non-const pointer. I can do the following:
const_cast<char*>(ss.str().c_str());
const_cast<char*>(s.c_str());
But to me that seems dangerous and probably won't even work correctly. Is there a good way to handle this that I've overlooked?
MaulingMonkey
MaulingMonkey
Quote:
Original post by Majirok
But to me that seems dangerous and probably won't even work correctly.


It'll work correctly on some implementations, but if you've got a roping or COW implementation things will go horribly wrong - in the best case. So yeah, don't do that!

Quote:
Is there a good way to handle this that I've overlooked?


Use a std::vector, it's guaranteed to have contiguous memory so you can treat it as a C array when interfacing with C code:

std::stringstream foo;//...std::string source = foo.str();std::vector< char > data( source.begin() , source.end() ); //fill data from sourcedata.resize( whatever_max_buffer_size_you_want );char * c_string = &(data[0]); //yes this is sane//use c_string to interface with C functionssource = &(data[0]); //if you want source cut off at the nullsource = std::string( data.begin() , data.end() ); //to get all the characters (including nulls and characters past them!)


Quote:
Original post by Majirok
I'm using an older C function in C++ (my first mistake, I know :P).


Considering how horribly backwards C++ bends in some places to support C compatibility, I wouldn't call this a mistake. It's called legacy support :-).
Majirok
Majirok
Thanks :)

Works nicely.
MaulingMonkey
MaulingMonkey
Quote:
Original post by Majirok
Thanks :)

Works nicely.


Glad to hear :-).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.