Joining Strings
You often need to put a text together from pieces: a first name and a last name, a greeting and a name. The function strcat (string concatenate, which means join) from string.h adds a text to the end of the text that's already in an array:
char full_name[30] = "Anna";
strcat(full_name, " ");
strcat(full_name, "Smith");
printf("%s\n", full_name);This prints:
Anna Smithstrcat finds the '\0' at the end of full_name and copies the new text there, including its own '\0'. The order is the same as with strcpy: first the array that changes, then the text to add. The second text stays as it was.
A common way to start is with an empty string, "", which holds only the '\0', and to add the pieces one by one. That comes in handy in a loop:
char stars[10] = "";
for (int i = 0; i < 3; i++) {
strcat(stars, "*");
printf("%s\n", stars);
}This prints:
*
**
***The array must have room for everything: the text that's already in it, the new text and one '\0'. "Anna Smith" needs 4 + 1 + 5 + 1 = 11 elements, so full_name[30] is more than enough. As with strcpy, the program doesn't compile here when Clang can see that the new text won't fit:
char greeting[8] = "Hello";
strcat(greeting, ", world!");main.c:6:5: error: 'strcat' will always overflow; destination buffer has size 8, but the source string has length 9 (including NUL byte) [-Werror,-Wfortify-source]Clang only checks the new text, though. When the array is already partly full, it often doesn't see the problem, and strcat writes past the end of the array without a word. So count how much room you need before joining, and when you aren't sure, make the array bigger.
Instructions
Before the last printf, join first_name, a space and last_name into full_name, using strcat three times. The output should be Name: Tom Baker.
Below that, create char laugh[20] = ""; and, in a for loop that runs 4 times, add "ha" to it. After the loop, print it: hahahaha.
Start programming for free
6/10