Solution for Exercise 13-09

ex1309

#include <stdio.h>
#include <string.h>

int main()
{
    char first[40];
    char last[20];

    printf("What is your first name? ");
    scanf("%s",first);
    printf("What is your last name? ");
    scanf("%s",last);
    strcat(first,last);
    printf("Pleased to meet you, %s!\n",first);
    return(0);
}

Output

What is your first name? Danny
What is your last name? Gookin
Pleased to meet you, DannyGookin!

Notes

* The string first is used at Line 13 because it's where both strings were copied.

* When you use the strcat() function, the second string is copied, or appended, to the end of the first string. Therefore, you must ensure that the first string, or char array, has enough storage space for the second string. The strcat() function doesn't check the space to ensure that enough storage exists, so be careful!

* You can use the malloc() function to allocate a buffers (storage places) in memory on-the-fly. This technique comes in handy when reading strings and gluing them together as you may not know the exact amount of storage space required. Refer to Chapter 20.