Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login Script does not compare string inputs as expected

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");
    }
}
like image 923
slither Avatar asked Mar 01 '26 02:03

slither


2 Answers

  • 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");
    }
}
like image 179
MikeCAT Avatar answered Mar 03 '26 16:03

MikeCAT


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,

  1. int main () should be int main (void) to conform to the standard.
  2. scanf("%s",&UsersInput); shold better be scanf("%29s",UsersInput); to avoid the possible buffer overflow by longer inputs.
  3. 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.

like image 30
Sourav Ghosh Avatar answered Mar 03 '26 18:03

Sourav Ghosh