strncmp problem #1

Problem: 

Accept if  given string is only "diarymilk". If the given string is "dairymilkshots" or "diarymilksilk", ignore it.

Program 1 

#include<stdio.h>
int main()
{
    char *given_string = "silkdiarymilkshots";
    char *string = "diarymilk";
    int len = strlen(string);
    if (strncmp(given_string, string, len) == 0) {
        printf("The given string - %s and string - %s are same\n", given_string, string);
    } else {
        printf("The given string - %s and string - %s are not same\n", given_string, string);
    }
    return 1;
}

Output:
The given string - silkdiarymilkshots and string - diarymilk are not same

In the above program, strncmp doesn't work for substring, because it compares always first 9 characters.

Program 2

#include<stdio.h>
int main()
{
    char *given_string = "diarymilkshots";
    char *string = "diarymilk";
    int len = strlen(string);
    if (strncmp(given_string, string, len) == 0) {
        printf("The given string - %s and string - %s are same\n", given_string, string);
    } else {
        printf("The given string - %s and string - %s are not same\n", given_string, string);
    }
    return 1;
}

Output:
The given string - diarymilkshots and string - diarymilk are same

In the second program, it compares the first 9 characters (string length of "string") with the given_string. So definitely this will match.

How to avoid this substring match problem ?

Let's recap what are the arguments passed in strncmp. 3rd argument is the key which should be able compare the given_string with \0. The second argument has exactly 10 characters (diarymilk\0), if we see it properly.   

Program 3

#include<stdio.h>
int main()
{
    char *given_string = "diarymilkshots";
    char *string = "diarymilk";
    int len = strlen(string) + 1;
    if (strncmp(given_string, string, len) == 0) {
        printf("The given string - %s and string - %s are same\n", given_string, string);
    } else {
        printf("The given string - %s and string - %s are not same\n", given_string, string);
    }
    return 1;
}

The given string - diarymilkshots and string - diarymilk are not same

Usecase 


This will be useful, if you are expecting a unique input from user.  

Comments