简体   繁体   English

加入2个const char * s c ++

[英]joining 2 const char*s c++

How can I combine two const char*s into a third? 如何将两个const char * s组合成第三个?

i'm trying to do this with this code: 我正在尝试使用此代码执行此操作:

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);

But I get this error: 但我得到这个错误:

'asprintf': identifier not found

I include stdio.h via this code: 我通过以下代码包含stdio.h:

#include <stdio.h>

Simple, just use C++: 简单,只需使用C ++:

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

const char* nName = name.c_str();

asprintf is a GNU extension. asprintf是一个GNU扩展。 You can instead use snprintf , or strncat , but you'll need to handle the memory management yourself: asprintf allocates the result for you. 您可以使用snprintfstrncat ,但您需要自己处理内存管理: asprintf为您分配结果。

Better to use std:string , which will make the code much easier. 最好使用std:string ,这将使代码更容易。

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

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

strcat. strcat的。

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

I will assume that you are using C, besides that you've tagged this question as C++. 我将假设你使用C,除此之外你已经将这个问题标记为C ++。 If you want C++, see Luchian's answer. 如果你想要C ++,请参阅Luchian的回答。

There are few errors in the code - the bigger error is that you didn't allocated memory for string pointing by pName . 代码中的错误很少 - 更大的错误是您没有为pName指定字符串指定内存。 Second error is that you are taking address of the nName variable, and not the address of reserved memory location in you asprintf function. 第二个错误是您正在获取nName变量的地址,而不是asprintf函数中的保留内存位置的地址。 Third error is that asprintf function is no standard C function, but the GNU extension and it might not be available on your compiler (you didn't say which is): http://linux.die.net/man/3/asprintf 第三个错误是asprintf函数不是标准的C函数,但GNU扩展可能在你的编译器上没有(你没说的是): http//linux.die.net/man/3/asprintf

You should use something like this: 你应该使用这样的东西:

#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);

Edit : I've read more about asprintf function now. 编辑 :我现在已经阅读了更多关于asprintf函数的内容。 You should pass address of your pointer in asprintf , but it should not be const char * but the char* , as memory location it points will change after allocating enough memory in asprintf . 你应该在asprintf传递指针的asprintf ,但它不应该是const char *而是char* ,因为它指向的内存位置会在asprintf分配足够的内存后发生变化。

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

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