Loading your workspace…
Loading your workspace…
Demonstrate the standard string functions strlen, strcpy, strcat and strcmp on two words entered by the user.
#include <stdio.h>
#include <string.h>
int main(void) {
char first[50], second[50], copy[100];
int cmp;
printf("Enter two words:\n");
if (scanf("%49s %49s", first, second) != 2) {
printf("Error: enter two words\n");
return 1;
}
printf("Length of first: %d\n", (int)strlen(first));
strcpy(copy, first);
strcat(copy, second);
printf("Joined: %s\n", copy);
printf("Length of joined: %d\n", (int)strlen(copy));
cmp = strcmp(first, second);
if (cmp < 0) {
printf("%s is less than %s\n", first, second);
} else if (cmp > 0) {
printf("%s is greater than %s\n", first, second);
} else {
printf("%s and %s are equal\n", first, second);
}
return 0;
}
Input
Good MorningOutput
Enter two words:
Length of first: 4
Joined: GoodMorning
Length of joined: 11
Good is less than MorningInput
abc abcOutput
Enter two words:
Length of first: 3
Joined: abcabc
Length of joined: 6
abc and abc are equalstrcpy must run before strcat, because strcat appends to whatever the destination already holds. copy is sized for both words plus the terminator, which is why it is larger than first and second.
strcmp returns a negative, zero or positive value according to the first differing character, so the comparison is made by its sign rather than by the exact number.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
Good Morning
Expected output
Enter two words: Length of first: 4 Joined: GoodMorning Length of joined: 11 Good is less than Morning
abc abc
Expected output
Enter two words: Length of first: 3 Joined: abcabc Length of joined: 6 abc and abc are equal
strcat writes past the existing text without checking the size, so the buffer must hold both strings and the terminator.
strcpy replaces the destination's contents; strcat appends to them.
A negative number, according to the first differing character.
strlen returns size_t, an unsigned type; the cast makes the printed value match the %d format.
string.h.
Back to all RCU 21BCA1C1P lab programs.