Andy
Andy

Reputation: 367

How to append const char* to a const char*

I am trying to append three different const char* variables into one. This is because a function from windows library takes the parameter LPCTSTR. I have the following code:

const char* path = "C:\\Users\\xxx\\Desktop\\";
const char* archivo = "vectors";
const char* extension = ".txt";

const char* fullPath =+ path;
fullPath =+ archivo;
fullPath =+ extension;

When I run it I get only the last (extension) added to to FullPath.

Upvotes: 1

Views: 25612

Answers (3)

David Schwartz
David Schwartz

Reputation: 182769

You need to allocate some space to hold the concatenated strings. Fortunately, C++ has the std::string class to do this for you.

std::string fullPath = path;
fullPath += archivo;
fullPath += extension;
const char *foo = fullPath.c_str();

Be aware that the space containing the concatenated strings is owned by fullPath and the pointer foo will only remain valid so long as fullPath is in scope and unmodified after the call to c_str.

Upvotes: 9

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

If you want to construct at compile-time a bunch of string literals, some of which are concatenations of other string literals, the most basic idiomatic low-maintenance technique is based on the good-old preprocessor

#define PATH "C:\\Users\\xxx\\Desktop\\"
#define NAME "vectors"
#define EXT  ".txt"

const char *path = PATH;
const char *archivo = NAME;
const char *extension = EXT;

const char *fullPath = PATH NAME EXT;

However, the same thing can be achieved in more moden way by using some constexpr and template meta-programming magic (see C++ concat two `const char` string literals).

Otherwise, you will have to resort to run-time concatenation (like std::string and such). But again, if the input is known at compile time, then a run-time solution is a "loser's way out" :)

Upvotes: 3

Rama
Rama

Reputation: 3305

When you use a const char* you can't change the chars to which are pointing. So append const char* to a const char* is not possible!

Upvotes: 0

Related Questions