Use C strcmp to compare two strings

Syntax

C strcmp function has the following syntax.

int strcmp(const char *str1, const char *str2);

C strcmp function is from header file string.h.

Description

C strcmp function lexicographically compares two strings and returns an integer based on the outcome:

Return

Value Meaning
< 0 str1 is less than str2
0str1 is equal to str2
>0 str1 is greater than str2

Example

Use C strcmp function to compare two strings.


#include<stdio.h>
#include<string.h>
/*from w w  w .  j a v a2 s . c  om*/
int main(void){
    char s[80];

    printf("Enter password: ");
    gets(s);
    if(strcmp(s, "pass")) {
      printf("Invalid Password\n");
      return 0;
    }
    return 1;
}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h