Vazhun
Vazhun

Reputation: 37

My string compare functions returns false even though the string is in the array

for the following code when I search for top hat I am not getting the desired result(i.e found) Instead the output is not found. I assume it is to do with how the char arrays are working behind the scenes, can anyone explain this to me.

#include <string.h>
#define MAX_LIMIT 20

int main(void)
{
    char strin[MAX_LIMIT];
    char numbers[6][10] = {"battleship","boat","cannon","iron","thimble","top hat"};
    printf("enter string to search:");
    scanf("%s", &strin);

    for(int i=0;i<6;i++)
    {
        if(strcmp(numbers[i],strin)==0)
        {
            printf("found\n");
            return 0;
        }
    }
    printf("not found\n");
    return 1;
}

Upvotes: 1

Views: 128

Answers (1)

user6177209
user6177209

Reputation: 11

scanf in scanf("%s", &strin); will read data from stdin until a whitespace character occurs.

As such, when you type into "top hat", scanf will read top not top hat.

I ran your code,value of strin was top. There is not such string in numbers.

strin is an array of char.The name of an char array is memory address.I think using strin instead of &strin is better.

If I want to search "top hat" in numbers,I will use fgets instead of scanf.Here is my code.It works well.

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

int main(void)
{
    char strin[MAX_LIMIT];
    char numbers[6][10] = {"battleship","boat","cannon","iron","thimble","top hat"};
    printf("enter string to search:");
//    scanf("%5s", &strin);
    fgets(strin, sizeof(strin), stdin);
    strin[strcspn(strin, "\n")] = '\0';


    for(int i=0;i<6;i++)
    {
        if(strcmp(numbers[i],strin)==0)
        {
            printf("found\n");
            return 0;
        }
    }
    printf("not found\n");

    return 0;
}

Upvotes: 1

Related Questions