Step 4 of 6
Compare strings correctly
Comparing two strings with == is one of the most common C bugs:
char cmd[20] = "quit";
if (cmd == "quit") { ... } // wrong: compares addresses
A string in C is an array, and using an array's name gives the address of its first character. So == asks "are these the same place in memory?", not "do they contain the same text?". They're different arrays, so it's false even though the letters match. The compiler warns: result of comparison against a string literal is unspecified.
To compare contents, use strcmp(a, b) from <string.h>. It compares character by character and returns:
0if the strings are equal,- a negative number if
acomes first alphabetically (by character codes), - a positive number if
acomes afterb.
#include <stdio.h>
#include <string.h>
int main(void) {
char answer[20];
scanf("%19s", answer);
if (strcmp(answer, "yes") == 0) {
printf("confirmed\n");
} else if (strcmp(answer, "no") == 0) {
printf("cancelled\n");
} else {
printf("please answer yes or no\n");
}
printf("%d\n", strcmp("apple", "banana") < 0);
return 0;
}
no
cancelled
1
Read it carefully
strcmp returns 0 for equal, and 0 means false in C. So if (strcmp(a, b)) runs when they're different, the opposite of what it looks like. Always write the comparison out: strcmp(a, b) == 0.
The comparison is exact and case sensitive: "Yes" and "yes" are different, because 'Y' and 'y' have different codes.
Your task
Read a command word. Print planting for plant, defusing for defuse, and unknown command for anything else.
Challenge 2
Read two player names and print which one comes first in dictionary order, as X comes first. If they're the same, print same name. Input ropz broky prints broky comes first.
Challenge 3
Read words until the word end (or until the input runs out) and count how many of them were gg. Input gg wp gg ez end gg prints 2, because the last gg comes after end.
Previous: Write your own strlen Next: Characters are numbers