Search code examples
arrayscpointerspasswords

How to Find if String exist in Array to Make Username and Password Program in C


//Username  and Password
#include<stdio.h>
#include <string.h>
void
main ()
{
  const char *arr[] =
    { "lonely_wolf69", "Alpha_male420", "jojo_rabbit77",
"secrethitleradmirer" };
  char a, *pass = "steverogersrox", n;
  int i, flag = 0;


  printf ("Enter Username: ");
  scanf ("%c", &a);

  if (memchr (arr, a, sizeof (arr)))
    {
      for (i = 0; i < 3; i++)
    {
      printf (" \n Enter Password: ");
      scanf ("%c", &n);
      if (n == *pass)
        {
          printf ("\n Login Successfull");
          break;
        }
      else
        {
          printf ("Wrong Password, Try Again.");
          flag++;
        }
    }


    }
  else
    printf ("User Not Found");

  if (flag == 3)
    printf ("\n You have been Blocked out of the system.");

}

Whatever I am entering, its Just Showing User Not Found. Note: I know.....very tedious....but looking to understand the concept first and clean up later, also any smarter Ideas are always encouraged.


Solution

  • After 3 Excruciating Days.....I Finally did it. Small But I'm really Proud

    ''''
    
        #include<stdio.h>
        #include<string.h>
        
        void
        main ()
        {
          int attempts = 3, i, n = 0;
          char user[20], pass[20];
          const char *user_list[] =
            { "lonely_wolf69", "Alpha_male420", "jojo_rabbit77",
            "secrethitleradmirer", "johnlennonbutpoor"
          };
        
        
          printf ("Enter Your Username: ");
          scanf ("%s", user);
        
        
        //for all elements of the list check if name present
        
          for (i = 0; i < sizeof (user_list) / sizeof (user_list[1]); i++)  //size of finds the lenght of array
            {
              if (strcmp (user, user_list[i]) == 0)
            {
              n = 1;
            }
            }
        
        
        
          if (n == 1)
            {
              while (attempts > 0)
            {
              printf ("\n Enter Password: ");
              scanf ("%s", pass);
        
              if (strcmp (pass, "love") == 0)
                {
                  printf ("Login Successful");
                  break;
                }
              else
                {
                  attempts--;
                  if (attempts == 0)
                break;
                  printf ("\n Wrong Password! Try Again. %d attempt(s) left",
                      attempts);
                }
            }
            }
        
        
          if (n != 1)
            printf ("User Not Found.");
        
        
        
          if (attempts == 0)
            printf ("You Have Been Blocked");
        }
        
        ''''