Char Comparison in C

I am trying to compare two characters to see if one of them is larger. To make sure they are equal, I used strcmp . Is there something like strcmp that I can use?

+7
source share
3 answers

A char variable is actually an 8-bit integral value. It will have values ​​from 0 to 255 . These are ASCII codes . 0 stands for C-null, and 255 stands for a blank character.

So, when you write the following assignment:

 char a = 'a'; 

This is the same as:

 char a = 97; 

So, you can compare two char variables using the operators > , < , == , <= , >= :

 char a = 'a'; char b = 'b'; if( a < b ) printf("%c is smaller than %c", a, b); if( a > b ) printf("%c is smaller than %c", a, b); if( a == b ) printf("%c is equal to %c", a, b); 
+9
source

In C, the char type has a numerical value, so the> operator will work just fine, for example

 #include <stdio.h> main() { char a='z'; char b='h'; if ( a > b ) { printf("%c greater than %c\n",a,b); } } 
+8
source

I believe that you are trying to compare two strings representing values, the function you are looking for:

 int atoi(const char *nptr); 

or

 long int strtol(const char *nptr, char **endptr, int base); 

these functions will allow you to convert the string to int / long int:

 int val = strtol("555", NULL, 10); 

and compare it with a different value.

 int main (int argc, char *argv[]) { long int val = 0; if (argc < 2) { fprintf(stderr, "Usage: %s number\n", argv[0]); exit(EXIT_FAILURE); } val = strtol(argv[1], NULL, 10); printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller"); return 0; } 
+1
source

All Articles