简体   繁体   中英

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.

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 .

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" :)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM