简体   繁体   English

如何将 const char* 附加到 const char*

[英]How to append const char* to a const char*

I am trying to append three different const char* variables into one.我试图将三个不同的 const char* 变量附加到一个中。 This is because a function from windows library takes the parameter LPCTSTR.这是因为 Windows 库中的函数采用参数 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.当我运行它时,我只将最后一个(扩展名)添加到 FullPath。

You need to allocate some space to hold the concatenated strings.您需要分配一些空间来保存连接的字符串。 Fortunately, C++ has the std::string class to do this for you.幸运的是,C++ 有std::string类可以为你做这件事。

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 .请注意,包含连接字符串的空间归fullPath所有,并且指针foo只有在调用c_strfullPath在范围内fullPath修改时才会保持有效。

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 ).然而,同样的事情可以通过使用一些constexpr和模板元编程魔法以更现代的方式实现(参见C++ concat two `const char` string literals )。

Otherwise, you will have to resort to run-time concatenation (like std::string and such).否则,您将不得不求助于运行时连接(如std::string等)。 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.当您使用const char*您无法更改指向的字符。 So append const char* to a const char* is not possible!所以将const char*附加到const char*是不可能的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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