mardi 4 août 2015

Concatenating string to char*

I am a C# developer and I find strange that when I run the following code in C++:

std::string original = "Hello";

std::string st = original + "World";
const char *c = st.c_str();

const char *c2 = (original + "World").c_str();

std::cout << "c  = '" << c << "'" << std::endl;
std::cout << "c2 = '" << c2 << "'" << std::endl;

I get the following output:

c  = 'HelloWorld'
c2 = ''

In C# a similar construct will result in c and c2 having the same value ("Hello World"). My guess would be that the scope of the result of (original + "World") ends on the right ), so c_str() is called on an invalid input. Is that correct? Is there a better way of achieving this other than creating variables to hold temporary results?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire