S. Agrawal S. Agrawal -4 years ago 102
C Question

I need to compare first three letters of a char array with a second string

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

int main ()
{
char *str1 = "EXIT";
int ret;

if (strncmp(str1, "EXI", 3))
printf("Return after if is %d", &ret);
else
printf("/nReturn after else is %d", &ret);
}


I need to compare a char array first three letters with the string, I am able to do it by comparing single single letter but not by using string function. I tried the above code but getting the negative result. Please help.

Answer Source

It seems you mean the following

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

int main( void )
{
    char *str1 = "EXIT";
    int ret;

    if ( ( ret = strncmp( str1, "EXI", 3 ) ) == 0 )
        printf( "Return after if is %d\n", ret );
    else
        printf( "Return after else is %d\n", ret);
}

From the output of the program it is seen that when n characters of two strings are equal the function strncmp returns 0. Otherwise it returns a negative value if the characters of the first string is less than the corresponding characters of the second string and a positive value if the characters of the first string is greater than the corresponding characters of the second string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download