user15380805
user15380805

Reputation:

How to compare 2 characters with strcmp in c?

I am trying to compare 2 characters with using strcmp. I gave statements but when I enter a and a as two characters, it gives -1. I don't see why? Here is my code:

#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20

int main()
{
    //comparing to characters
    char c1[1], c2[1];
    int result;
    //asking user to enter characters respectively
    printf("6.Enter the first character you want to compare: \n");
    scanf("%s", c1);
    getchar();
    printf("7.Enter the second character you want to compare: \n");
    scanf("%s", c2);
    getchar();
    //comparing c1 with c2 using strcmp
    //result = strcmp(c1, c2);
    if (strcmp(c1, c2) == 0)
    {
        printf("0\n");
    }
    else if (c1 < c2)
    {
        printf("-1\n");
    }
    else
    {
        printf("1\n");
    }
}

Upvotes: 0

Views: 723

Answers (3)

mkayaalp
mkayaalp

Reputation: 2736

You have a buffer overflow. Don't use scanf.

Even if your input was only a single char, you would still need another in c1 and c2 for the termination: '\0':

    char c1[2], c2[2];

Also, you are comparing the memory addresses since c1 and c2 are char arrays. Compare the chars instead: c1[0] < c2[0]

    if (strcmp(c1, c2) == 0)
  {
    printf("0\n");
  }
    else if (c1[0] < c2[0])
  {
    printf("-1\n");
  }
    else
  {
    printf("1\n");
  }

Upvotes: 2

user15380805
user15380805

Reputation:

I made a small improvement on @mkayaalp 's answer and my code worked properly. Here:

    if (c1[0] == c2[0])
  {
    printf("0\n");
  }
    else if (c1[0] < c2[0])
  {
    printf("-1\n");
  }
    else
  {
    printf("1\n");
  }

I also changed the if part.

Upvotes: 0

hrsh
hrsh

Reputation: 108

This is happening because: you doing getchar after doing a scanf! The second input will be taken in by getchar and c2 will be allocated some garbage value.

Also: You should compare the characters: so c1[0] < c2[0] rather than c1 < c2

Upvotes: 0

Related Questions