1

I want to create a "fullname" variable from multiple strings. Something like this:

strcpy (fullname, firstname);
strcat (fullname, separator); // separator is initialized at " "
strcat (fullname, middlename);
strcat (fullname, separator);
strcat (fullname, lastname);

This code is repeated at multiple places in my project. I was gonna do a function that does exactly that, but now I wonder if there isn't a better way to do it.

Any ideas?

2

3 Answers 3

3

You can do also:

sprintf (fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

But always make sure that the fullname points to a buffer which can accommodate the total length of all the things you are concatenating.

int size;
int *fullname;
size = strlen (firstname) + strlen (separator) + strlen (middlename) + strlen (separator) + strlen (lastname) + 1;

fullname = malloc (sizeof (char) * size);

sprintf (fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

/* Work */

free (fullname);
Sign up to request clarification or add additional context in comments.

1 Comment

snprintf includes a size argument and should be used in cases where the destination string has a fixed maximum size.
1
sprintf(fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

If separator is always " " then you can do

sprintf(fullname, "%s %s %s", firstname, middlename, lastname);

Though you need to ensure that fullname has sufficient space.

Comments

1

There's stpcpy (became standard in posix 2008). It'd look like this:

char *ptr = fullname:
ptr = stpcpy (ptr, firstname);
ptr = stpcpy (ptr, separator);
ptr = stpcpy (ptr, middlename);
ptr = stpcpy (ptr, separator);
ptr = stpcpy (ptr, lastname);

If you also need to take care not to overflow fullname, use stpncpy instead:

char *ptr = fullname;
char *end = fullname + sizeof(fullname) - 1;
ptr = stpncpy (ptr, firstname, end - ptr);
ptr = stpncpy (ptr, separator, end - ptr);
ptr = stpncpy (ptr, middlename, end - ptr);
ptr = stpncpy (ptr, separator, end - ptr);
ptr = stpncpy (ptr, lastname, end - ptr);
*ptr = '\0'; // Or optionally error if ptr >= end

snprintf can also be a good choice:

snprintf(fullname, sizeof(fullname), "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.