Search code examples
cstringstrcmp

why wont strcmp() in password work?


Why does it always show Invalid Password? It works in my other program but in this one it doesn't! I literally cant figure out why.

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#define MAXLTR 15
int login(void);
void welcome(void);
void gotoxy(int x,int y);

int main(void)
{   
    char password[MAXLTR];
    printf("\nEnter password: ");
    //scanf("\n%s",&password);
    ltrcntr = 0;
    while(buffer != 13)
    {
        buffer = getch();
        if(buffer == 13)
                  break;
        printf("\b**");
        password[ltrcntr] = buffer;
        ltrcntr++;
    }
    if(strcmp(password,"dlsu") == 0)
    {
        system("cls");
        welcome();
    }
    else
        printf("\nInvalid Password, please rerun the program.\n");


}
void gotoxy(int x, int y)
{
     HANDLE eric;
     COORD pogi;
     pogi.X = x;
     pogi.Y =y;
     eric = GetStdHandle
     (STD_OUTPUT_HANDLE);
     SetConsoleCursorPosition
     (eric, pogi);
}
int login(void)
{
    char password[MAXLTR],buffer;
    int ltrcntr = 0;
    printf("Enter password: ");
    while(buffer != 13)
    {
        buffer = getch();
        if(buffer == 13)
                  break;
        printf("\b**");
        password[ltrcntr] = buffer;
        ltrcntr++;
    }
    if(strcmp(password,"dlsu")==0)
        return 1;

}

void welcome(void)
{
    system("Color 4F");
    gotoxy(35,56);
    printf("\nWelcome to SPACE INVADERS!");
}

Solution

  • C strings are NULL terminated (i.e., the last character is \0). All C functions which operate on strings expect this because it is the only way to know where the string ends. You array could be filled with anything as it is uninitialized. Try this:

    char password[MAXLTR] = {0};
    

    strcmp expects a NULL terminated string. Also, if a carriage return is never entered (and I don't even see where buffer is declared...) you will overrun your password buffer.