Skip to main content
gamedev.net
🔒 Locked

string to char*

Started by Peaceman Jun 11, 2002 at 10:40 AM 8 replies 400+ views
Original Post
Peaceman
Peaceman
Hi guys, I need to convert a string(STL) to a normal char * or if it helps just to a char[128]. I''d appreciate some help on this one, as I couldn''t find a conversionroutine from string to char. thx
IDispatch
IDispatch
This should do it:

sMyString.c_str();

DerekSaw
DerekSaw

...
std::string abc = "Some string";
char *p;

p = abc.c_str();
//or
p = abc.data();


[edited by - DerekSaw on June 11, 2002 11:49:01 AM]
"after many years of singularity, i'm still searching n the event horizon" o
Peaceman
Peaceman
thx for your fast replies
Peaceman
Peaceman
If I use this code:


...
std::string abc = "Some string";
char *p;

p = abc.c_str();
//or
p = abc.data();

I get "error C2440: ''='' : cannot convert from ''const char *'' to ''char *''"

Why?
SabreMan
SabreMan
Because c_str() returns a const char*, of course. If you are passing to a legacy API, and that API modifies the c-string, then you will need to make a copy. If the API does not modify the c-string, then you can perform a const_cast.
siaspete
siaspete
Are you trying to copy the string to an array of chars, or get a pointer to it?

If you''re trying to copy it, you must do something like this...

char array[100];
strcpy (array, str.c_str ());

If you''re trying to get a pointer to it, I recommend against it, as the pointer you get is not necessarily going to be valid for any length of time.


Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
Atavist
Atavist
Usually you would use abc.c_str() to compare against another string, and being const char* is best for a compare.
If you want to make a seperate copy of the string, you do just that you make a copy:


std::string abc = "Some string";
char *p;
int len;

len = abc.length();
p = new char[len+1];
strcpy(p,abc.c_str());

//later on make sure to
delete [] p;


Now you have a copy thats independant of abc.

edit: love these simple questions its easy for lots of people to answer

[edited by - atavist on June 11, 2002 12:29:43 PM]
Just because the church was wrong doesn't mean Galileo wasn't a heretic.It just means he was a heretic who was right.
DerekSaw
DerekSaw
quote:
Original post by Peaceman
If I use this code:


...
std::string abc = "Some string";
char *p;

p = abc.c_str();
//or
p = abc.data();

I get "error C2440: ''='' : cannot convert from ''const char *'' to ''char *''"

Why?



Oooops... forgot that it return const char *
"after many years of singularity, i'm still searching n the event horizon" o

Topic Locked

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

Sign in to reply to this topic.