Comparing Strings
Did the user type the right password? (In a real program, the user would type it in. Programs on this site get their data from variables.) The first idea is to compare the strings with ==. That compiles here, but it doesn't do what you'd expect:
char password[] = "sesame";
char attempt[] = "sesame";
if (attempt == password) {
printf("Access granted\n");
} else {
printf("Access denied\n");
}This prints:
Access deniedBoth arrays hold the same text, and still the program says they're different. That's because == doesn't compare the characters of two arrays. It only asks whether both sides are the same array, the same place in the computer's memory. Every array has its own place in memory, so for two different arrays, the answer is always “no”. (Clang warns about it, but this site doesn't show warnings.)
To compare texts, use the function strcmp (string compare) from string.h. It goes through both strings character by character and gives a whole number: 0 when the texts are the same:
char password[] = "sesame";
char attempt[] = "sesame";
if (strcmp(attempt, password) == 0) {
printf("Access granted\n");
} else {
printf("Access denied\n");
}This prints:
Access grantedCareful: here, 0 means “the same”, which is the opposite of what you might expect. In a condition, 0 is false, so if (strcmp(attempt, password)) would mean “if the texts are different”. Always write == 0, so that the code says exactly what it does.
When the texts are different, the number tells you their alphabetical order. It's negative when the first text comes before the second one, and positive when it comes after it. Don't count on a particular number, such as -1. Only check whether it's less than or greater than 0:
char first[] = "apple";
char second[] = "banana";
if (strcmp(first, second) < 0) {
printf("%s comes first\n", first);
} else {
printf("%s comes first\n", second);
}This prints:
apple comes firststrcmp compares characters as numbers: 'A' is 65, 'B' is 66 and so on, and the lowercase letters start at 'a', which is 97. So uppercase and lowercase letters are different: strcmp("Sesame", "sesame") isn't 0. And every uppercase letter comes before every lowercase one, so for strcmp, "Zebra" comes before "apple".
Instructions
The attempt is right, but the program prints Access denied. Fix the condition: compare the texts with strcmp and == 0. Then the program prints Access granted.
Below the condition, create the names of two players, char player1[] = "Mia"; and char player2[] = "Leo";. With strcmp, print the one that comes first in alphabetical order, as Leo comes first.
Start programming for free
7/10