So i want to make a login script and I have coded it but when I run it, it always says "Wrong Username" even though it is right.
This is my code
#include <stdio.h>
#include <stdlib.h>
#define MYNAME "SLITHER" //Defines SLITHER so u can put %s yo use it
#define HackerNum 1338
/*
Welcome To slithers Program
I will be coding what ever I like
c:
*/
void LoginScript ();
char RealUsername[20] = "slither";
char UsersInput[30];
int main ()
{
printf("Welcome To /bin V1");
printf("\n Made By slither!\n");
LoginScript ();
}
void LoginScript ()
{
printf("Please Login\n");
printf("Username: ");
scanf("%s",&UsersInput);
//printf("You Entered %s", UsersInput); This says what you printed
if (UsersInput == RealUsername)
{
printf("Logged in");
}
else
{
printf("Wrong Username");
}
}
scanf("%s",&UsersInput); is undefined behavior due to type mismatch (char* expected, got char (*)[30])UsersInput == RealUsername is comparation of pointers, not contents of strings. strcmp() is useful to compare strings.Add #include <string.h> at the beginning of the code and try this:
void LoginScript ()
{
printf("Please Login\n");
printf("Username: ");
scanf("%29s",UsersInput); // add 29 (maximum length to read) to avoid buffer overrun
//printf("You Entered %s", UsersInput); This says what you printed
if (strcmp(UsersInput, RealUsername) == 0)
{
printf("Logged in");
}
else
{
printf("Wrong Username");
}
}
it always says "Wrong Username" even though it is right.
Yes, that's what it should. In your code,
if (UsersInput == RealUsername)
is wrong. That's not how you should be comparing strings. This statement actually try to compare the pointers themselves, not the "strings" they contain. That's why, your if check does not work as they intend to.
You need to use strcmp() for that (prototyped in string.h), like
if ( !strcmp(UsersInput, RealUsername) )
{
printf("Logged in\n");
}
else
{
printf("Wrong Username\n");
}
Having said that,
int main () should be int main (void) to conform to the standard.scanf("%s",&UsersInput); shold better be scanf("%29s",UsersInput); to avoid the possible buffer overflow by longer inputs.While initializing an array at the time of definition, it's better to leave the size allocation to the compiler, for example,
char RealUsername[ ] = "slither";
is considered better over
char RealUsername[20] = "slither";
At times, it saves the headache of forgetting the count for the size of the terminating null character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With