C - Comparing text to check password

Introduction

Strings are compared by using the strcmp() function and all its cousins: strncmp(), strcasecmp(), and strncasecmp().

The string-comparison functions return an int value based on the result of the comparison:

  • 0 for when the strings are equal, or
  • a higher or lower int value based on whether the first string's value is greater than or less than the second string.

Most of the time, you just check for 0.

The following code uses the strcmp() function compare the initialized string password with whatever text is read, which is stored in the input array.

The result of that operation is stored in the match variable, which is used in an if-else decision to display the results.

Demo

#include <stdio.h> 
#include <string.h> 

int main() // www. ja  v  a2  s.c o  m
{ 
      char password[]="1234"; 
      char input[15]; 
      int match; 

      printf("Password: "); 
      scanf("%s",input); 

      match=strcmp(input,password); 
      if(match==0) 
          puts("Password accepted"); 
      else 
          puts("Invalid password. Alert the authorities."); 

      return(0); 
}

Result

Related Topic