I need to concatenate two const chars like these:
const char *one = "Hello ";
const char *two = "World";
How might I go about doing that?
I am passed these char*
s from a third-party library with a C interface so I can't simply use std::string
instead.
Using
std::string
:If you don't know the size of the strings, you can do something like this:
In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:
will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:
First of all, you have to create some dynamic memory space. Then you can just strcat the two strings into it. Or you can use the c++ "string" class. The old-school C way:
New C++ way
One more example:
But unless you specifically don't want or can't use the C++ standard library, using
std::string
is probably safer.It seems like you're using C++ with a C library and therefore you need to work with
const char *
.I suggest wrapping those
const char *
intostd::string
: