DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   converting std::string to const chars? (http://www.daniweb.com/forums/thread45124.html)

iamthwee May 9th, 2006 5:12 pm
converting std::string to const chars?
 
Hullo, I need help here I can't get this to work. I'm not sure if the code is correct. Any help would be most appreciated. I basically wanna convert a std::string to a const char array.

#include <string>
#include <iostream>

void bull(char[]);

int main()
{
  std::string Yo_momma = "iz fat";
 
  bull(Yo_momma.c_str()); //<--error here
 
  std::cin.get();
  return 0;
}

void bull( char crap[] )
{
    std::cout << crap;
}

My errors...

 In function `int main()': 
 invalid conversion from `const char*' to `char*'
 initializing argument 1 of `void bull(char*)'

I'm using windows xp and Dev-cpp

God bless.

iamthwee May 9th, 2006 5:26 pm
Re: converting std::string to const chars?
 
*Sigh* gotta love google.

char buf[255];
 
  std::strcpy( buf, Yo_momma.c_str() );
  bull(buf);

This works apparently?

Lerner May 9th, 2006 6:05 pm
Re: converting std::string to const chars?
 
c_str() returns a const char []. bull() takes a char [] as a parameter. That means that any changes made to char[] in bull() should be valid changes in c_str(). However since c_str() returns a const char [] it can't be changed. Therefore the compiler throws an error. Hence, you have to copy c_str() to a char [] before passing it to bull(). You could also try to temporarily ignore the constantness of c_str() when passing it to bull() by using the using the C++ syntax const_cast before the call c_str().

winbatch May 14th, 2006 9:01 am
Re: converting std::string to const chars?
 
Quote:

void bull(char[]);


void bull( char crap[] )
{
std::cout << crap;
}
Assuming you won't in fact attempt to change 'crap' inside the 'bull' function, simply change the above to:
void bull( const char[] )
and
void bull( const char crap[] )
{
    std::cout << crap;
}

Jessehk May 14th, 2006 10:57 am
Re: converting std::string to const chars?
 
I know this works, but I don't know if it is a best practise.

#include <iostream>
#include <string>

void changeFirstLetter(char *str) {
    *str = 'J';
}

int main() {
    std::string msg = "Hello, world!";
   
    std::cout << msg << std::endl;
    changeFirstLetter(const_cast<char *>(msg.c_str()));
    std::cout << msg << std::endl;
}

OUTPUT:
Hello, world!
Jello, world!


All times are GMT -4. The time now is 6:47 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC