Using strcmp()
Part of the Logic & Flow section of Coddy's C journey — lesson 18 of 63.
You've learned how to join strings with strcat(), but what if you need to determine whether two strings contain exactly the same text? In C, you cannot use the equality operator (==) to compare strings because it only compares memory addresses, not the actual content.
The strcmp() function from the <string.h> library solves this problem by comparing two strings character by character. It performs what's called a lexicographical comparison - essentially comparing strings in dictionary order.
#include <stdio.h>
#include <string.h>
char word1[] = "apple";
char word2[] = "apple";
int result = strcmp(word1, word2); // Returns 0 (strings are equal)The strcmp() function returns three different types of values: it returns 0 if the strings are identical, a negative value if the first string comes before the second alphabetically, and a positive value if the first string comes after the second alphabetically.
This function is essential for making decisions based on string content, such as validating user input, sorting text data, or implementing search functionality in your programs.
Challenge
EasyWrite a C program that implements a simple password verification system using the strcmp() function. Your program should:
- Read an integer
nrepresenting the number of login attempts to process - For each login attempt:
- Read a username from input
- Read a password from input
- Use
strcmp()to compare the username with "admin" - Use
strcmp()to compare the password with "secret123" - Print the appropriate message based on the comparison results
- After processing all attempts, count and display how many successful logins occurred
The login validation logic should be:
- If both username and password are correct: print "Login successful"
- If username is correct but password is wrong: print "Invalid password"
- If username is wrong but password is correct: print "Invalid username"
- If both username and password are wrong: print "Invalid credentials"
Remember to include the <string.h> header to use the strcmp() function.
Your output should display the results in the following format:
[Login result message]
[Login result message]
...
Total successful logins: [count]For example, if the input is:
4
admin
secret123
user
password
admin
wrong
guest
secret123Your output should be:
Login successful
Invalid credentials
Invalid password
Invalid username
Total successful logins: 1This challenge tests your understanding of using strcmp() to compare strings for equality, implementing conditional logic based on string comparison results, and counting occurrences based on comparison outcomes.
Cheat sheet
The strcmp() function from <string.h> compares two strings character by character using lexicographical comparison:
#include <string.h>
char word1[] = "apple";
char word2[] = "apple";
int result = strcmp(word1, word2);strcmp() returns:
0if strings are identical- Negative value if first string comes before second alphabetically
- Positive value if first string comes after second alphabetically
Cannot use == to compare strings in C as it only compares memory addresses, not content.
Try it yourself
#include <stdio.h>
#include <string.h>
int main() {
int n;
scanf("%d", &n);
char username[100];
char password[100];
int successful_logins = 0;
// TODO: Write your code here
// Process each login attempt using strcmp() function
// Compare username with "admin" and password with "secret123"
// Print appropriate messages and count successful logins
printf("Total successful logins: %d\n", successful_logins);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions