加入2个const char * s c ++

时间:2012-07-18 21:50:23

标签: c++ string char string-concatenation

如何将两个const char * s组合成第三个?

我正在尝试使用此代码执行此操作:

const char* pName = "Foo"
printf("\nMy name is %s.\n\n\n",pName);
const char* nName;
int num_chars = asprintf(&nName, "%s%s", "Somebody known as ", pName);

但是我收到了这个错误:

'asprintf': identifier not found

我通过以下代码包含stdio.h:

#include <stdio.h>

4 个答案:

答案 0 :(得分:9)

简单,只需使用C ++:

const char* pName = "Foo"
std::string name("Somebody known as ");
name += pName;

const char* nName = name.c_str();

答案 1 :(得分:7)

asprintf是GNU扩展。您可以使用snprintf或  strncat,但您需要自己处理内存管理:asprintf为您分配结果。

最好使用std:string,这将使代码更容易。

答案 2 :(得分:2)

sprintf(snprintf)或strcat(strncat)。 sprintf的。

sprintf(nName, "%s%s", "Somebody known as ", pName);

strcat的。

strcpy(nName, "Somebody known as ");
strcat(nName, pName);

答案 3 :(得分:1)

我会假设您使用C,除此之外您已将此问题标记为C ++。如果你想要C ++,请参阅Luchian的答案。

代码中的错误很少 - 更大的错误是你没有为pName的字符串指向分配内存。第二个错误是您正在获取nName变量的地址,而不是您asprintf函数中保留内存位置的地址。第三个错误是asprintf函数不是标准C函数,但GNU扩展可能在编译器上不可用(你没说的是):http://linux.die.net/man/3/asprintf

你应该使用这样的东西:

#include <stdio.h>
const char* pName = "Foo"
printf("\nMy name is %s.\n\n\n",pName);
char nName[30];
int num_chars = sprintf(nName, "%s%s", "Somebody known as ", pName);

编辑:我现在已经阅读了有关asprintf功能的更多信息。您应该在asprintf中传递指针的地址,但它不应该是const char *而是char*,因为它指向的内存位置会在asprintf中分配足够的内存后发生变化。