'Password function
I am very *very new to programming especially using C. I'm trying to create a password function that can read the user name and password from a file and compare it to the username and password entered. The problem is that the code prints the error message even when the password and username I entered is correct.
void Passwrd ()
{
struct Password pssword[40];
char username1[20];
int passw0rd, c;
bool condition= false;
printf ("Hello. Please enter the username.\n");
scanf ("%s", &username1);
printf ("Hello. Please enter the password\n");
scanf ("%d",&passw0rd);
c=0;
FILE*password;
password= fopen ("Passwords.txt", "r");
while (condition== false ){
while(!feof(password)){
fscanf (password,"%s %d \n", &pssword[c].username,&pssword[c].passwrd);
if ((pssword[c].username==username1) && (pssword[c].passwrd== passw0rd)){
printf("Thank you! Please continue the program\n");
feof(password);
condition= true;
}
else if ((pssword[c].username!=username1) && (pssword[c].passwrd!=passw0rd)){
printf("Error!!The password or username is invalid\n");
condition= false;
c++;
}
}
fclose (password);
}
}
Solution 1:[1]
One reason why your code isn't working is that you're comparing strings with ==. A string is a char*, which is just a memory address. When using ==, you compare the memory addresses. Even if the two strings are the same, they won't be in the same place in memory, so pssword[c].username will not == username1.
To fix this, use the strcmp() function, or even better, strncmp().
One other thing to note: you have a logic error. In your if/else if, you've handled what happens if:
- both the username and password are correct
- both the username and password are wrong
If one is right and the other is wrong, neither condition will be met, so no message will be printed. Just use else instead of else if in this case, like so:
if ((pssword[c].username==username1) && (pssword[c].passwrd== passw0rd)){
printf("Thank you! Please continue the program\n");
feof(password);
condition= true;
}
else {
printf("Error!!The password or username is invalid\n");
condition= false;
c++;
}
Also, you may want to consider renaming your variables a bit. Using a 0 instead of an o and misspelling password doesn't make it readable. Maybe something like correct_password, correct_user, input[c].password, and input[c].user would be easier to follow and debug.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tjcaul |
