Reputation: 23
This is a simple C authentication program that went wrong. It's reading the strings from the console as a username and password as input correct, but the username input has becomes blank space string. What might be the mistake?
#include <stdio.h>
int main()
{
char username[4];
char password[8];
printf("Enter username: ");
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);
if (username == "ojas" && password == "ojas1234")
{
printf("Access granted!");
}
else
{
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
Enter username: ojas
Enter password: ojas1234
and ojas1234
Access denied
Upvotes: 2
Views: 137
Reputation: 477
To compare two strings, you can use strcmp()
function. This will compare the two strings character by character. Don't forget to use the header file string.h
You can't use equal sign to compare two strings because string literals are identical and a string in C is a character array and it refers to an address. So if you use "==" signs, you will end up comparing two addresses.
Though the above mistake is corrected, still you will get the output as Access Denied. That is because your buffer overflows. So, define a large number for your username and password char arrays.
The below code might help you to fix these issues.
#include<stdio.h>
#include<string.h>
#define LEN 50
int main()
{
char username[LEN];
char password[LEN];
printf("Enter username: ");
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);
if ((strcmp(username,"ojas") == 0) && (strcmp(password,"ojas1234") == 0))
{
printf("Access granted!");
}
else
{
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
Upvotes: 1
Reputation: 121649
There are several problems with your code, including:
SUGGESTED CHANGES:
#include <stdio.h>
#include <string.h>
#define MAX_STRING 80
int main()
{
char username[MAX_STRING];
char password[MAX_STRING];
printf("Enter username: ");
fgets(username, MAX_STRING, stdin);
strtok(username, "\n");
printf("Enter password: ");
fgets(password, MAX_STRING, stdin);
strtok(password, "\n");
if ((strcmp(username, "ojas") == 0) && (strcmp(password, "ojas1234") == 0)){
printf("Access granted!");
}
else {
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
Upvotes: 2