How concatenate a string and a const char?

string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();

or without modifying a:

string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();

Little edit, to match amount of information given by 111111.

When you already have strings (or const char *s, but I recommend casting the latter to the former), you can just “sum” them up to form longer string. But, if you want to append something more than just string you already have, you can use stringstream and it’s operator<<, which works exactly as cout‘s one, but doesn’t print the text to standard output (i.e. console), but to it’s internal buffer and you can use it’s .str() method to get std::string from it.

std::string::c_str() function returns pointer to const char buffer (i.e. const char *) of string contained within it, that is null-terminated. You can then use it as any other const char * variable.

Leave a Comment