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.
If you are using C++, why don't you use
std::string
instead of C-style strings?If you need to pass this string to a C-function, simply pass
three.c_str()
The C way:
The C++ way:
The compile-time way:
You can use
strstream
. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.This will write
one
and thentwo
into the stream, and append a terminating\0
usingstd::ends
. In case both strings could end up writing exactly99
characters - so no space would be left writing\0
- we write one manually at the last position.Update: changed
string total = string(one) + string(two);
tostring total( string(one) + two );
for performance reasons (avoids construction of string two and temporary string total)Connecting two constant char pointer without using strcpy command in the dynamic allocation of memory: