Apply String Comparison in a Real-world Scenario
In this step, you will create a simple password management system that demonstrates practical string comparison techniques.
- Create a new file named
password-manager.c
in the ~/project
directory:
cd ~/project
touch password-manager.c
- Open the file in WebIDE and add the following code:
#include <stdio.h>
#include <string.h>
#define MAX_USERS 3
#define MAX_USERNAME 50
#define MAX_PASSWORD 50
// User structure to store credentials
struct User {
char username[MAX_USERNAME];
char password[MAX_PASSWORD];
char role[20];
};
int main() {
// Predefined user database
struct User users[MAX_USERS] = {
{"admin", "admin123", "administrator"},
{"manager", "manager456", "manager"},
{"user", "user789", "regular"}
};
char input_username[MAX_USERNAME];
char input_password[MAX_PASSWORD];
int login_success = 0;
printf("=== Simple Password Management System ===\n");
printf("Enter username: ");
scanf("%s", input_username);
printf("Enter password: ");
scanf("%s", input_password);
// Authenticate user with string comparison
for (int i = 0; i < MAX_USERS; i++) {
if (strcmp(users[i].username, input_username) == 0) {
if (strcmp(users[i].password, input_password) == 0) {
printf("Login Successful!\n");
printf("Role: %s\n", users[i].role);
login_success = 1;
break;
}
}
}
if (!login_success) {
printf("Login Failed. Invalid username or password.\n");
}
return 0;
}
- Compile the program:
gcc password-manager.c -o password-manager
- Run the program:
./password-manager
Example interactions:
=== Simple Password Management System ===
Enter username: admin
Enter password: admin123
Login Successful!
Role: administrator
Enter username: user
Enter password: wrongpassword
Login Failed. Invalid username or password.
Key points about this real-world scenario:
- Uses
strcmp()
for secure credential verification
- Demonstrates practical application of string comparison
- Implements a simple authentication system
- Shows how to compare multiple user credentials