# Getting char* from std::string?

## Recommended Posts

Kind of an obvious question, anyways I read the STL documentation, and I assumed that the way was
 class A
{
private:
string s;
public:
A(string k) { s=k; }
void B()
{
printf(s.c_str());
}
};


But it gives random chars or crashes, tipical bad char pointer issues. So what's the actual solution of what I am doing incorrectly? Edit: I am not really using printf it is another function that takes char* (it is the hge method for changing the windows' title)

##### Share on other sites
#include <string>#include <iostream>using   std::string;using   std::cout;class A{     string  s;public:     A(string k):s(k){}     void B(){ cout << s; } };

[edit: Note that string.c_str() returns a const char *, so you'll need to copy it into a normal char * if the function will indeed modify the char*.]

##### Share on other sites
I don't want to print the string, I want to use it on a method that takes char*, I used printf as an example

Quote:
 [edit: Note that string.c_str() returns a const char *, so you'll need to copy it into a normal char * if the function will indeed modify the char*.]

That's an advance, although I don't think that function modiffies the char would try to strcpy this time.

Although I guess that if I have to use strcpy on the result of c_str() it would probably have more sense to manually copying the characters of the std::string into the *char array

##### Share on other sites
Isn't it a problem of caractere set ?

##### Share on other sites
Quote:
 Original post by VexorianBut it gives random chars or crashes, tipical bad char pointer issues.

Well, in the case of printf in particular, the const char * that you pass to it also is parsed for format codes, ie. %[flags][width][.precision][modifiers]type. If the string is more than just text, this could be the source of your random characters.

##### Share on other sites
Well I am just using a test string "hello" and not really using printf just any function that takes char*

##### Share on other sites
OK, well post the code you use to assign the std::string and the code that actually changes the window text. Sounds like there's an error in one of these two places.

##### Share on other sites
Well I don't really remember it correctly but it was something like this, at least the lines where I modiffy the strings are there.

class hint: public gobject{ private:     unsigned int bcolor;     unsigned int fcolor;     string text; public:      hint(square* sq,string s)      {          GroundObjectInit(sq);          bcolor=0xFFFFFFFF;          fcolor=0x00000000;          text=s;      }      void OnEnter(object *obj)      {          GetGame()->hge->System_SetState(SYSTEM_TITLE,text.c_str());      }      void OnLeave(object *obj)      {          GetGame()->hge->System_SetState(SYSTEM_TITLE,"Xye");      }};

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628284
• Total Posts
2981829

• 10
• 10
• 10
• 11
• 17