Member Avatar for iamthwee

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.

Recommended Answers

All 4 Replies

Member Avatar for iamthwee

*Sigh* gotta love google.

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

This works apparently?

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().

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;
}

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!
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.