简体   繁体   中英

joining 2 const char*s c++

How can I combine two const char*s into a third?

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:

#include <stdio.h>

Simple, just use C++:

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

const char* nName = name.c_str();

asprintf is a GNU extension. You can instead use snprintf , or strncat , but you'll need to handle the memory management yourself: asprintf allocates the result for you.

Better to use std:string , which will make the code much easier.

sprintf(snprintf) or strcat(strncat). sprintf.

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

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++. If you want C++, see Luchian's answer.

There are few errors in the code - the bigger error is that you didn't allocated memory for string pointing by 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. 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

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. 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 .

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