Skip to main content
gamedev.net
🔒 Locked

string to char conversion

Started by 3dmodelerguy 2 replies 600+ views
Original Post
3dmodelerguy
3dmodelerguy
is there any way to convert a string to a const char *?
Evil Steve
Evil Steve
A std::string? Yes, you can get a const char* or a non-const char*, but I believe the non-const version isn't standard (but it works on every STL implementation I've seen - where a string is a consecutive block of memory)
std::string str = "Hello world";const char* szConst = str.c_str();char* szNonConst = &str[0];
Zahlman
Zahlman
!!

You should not be able to do that without a const_cast, and There Be Dragons(TM). You are asking to be able to modify the underlying string data that the std::string object is supposed to be managing for you. And what if you do something to it that violates one of the invariants of the std::string?

If you really, really require mutable data, make a copy of it:

// This is completely off the top of my head and 0% guaranteed.template <typename CSM, typename R>// CSM is a CharStarManipulator; any pointer to a function accepting char* and// returning R, or any functor with operator() of that signature.// There is probably a more elegant way of setting this up...inline R wrapper(CSM manipulator, string& input) {  char* buf = new char[input.size() + 1];  strcpy(buf, input.c_str());  R result = manipulator(buf);  // Cause changes to the buffer to be reflected in the string  input.assign(buf);  return result;}
chollida1
chollida1
Have you seen the definition of main, its a common/general as you get. I seem to recall a char/wchar_t in there:)

Cheers
Chris
CheersChris

Topic Locked

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

Sign in to reply to this topic.