0

How to search for the whole word in an 2d array of strings. This code outputs me only the first letter of the word I enter.

can anyone help me with this ?

And how is that index passed in a function only the index I find form this search .

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30

int main (void)
{
    int i;
    char found_name;
    char name[PEOPLE][LEN_NAME]= {"John Lucas","Armanod Jonas",
                                "Jack Richard","Donovan Truck"};

    printf("What name do you want to search?\n>");
    scanf("\n%s", &found_name);
    for (i = 0 ; i < PEOPLE; i ++)
    {
        if (strchr(name[i], found_name ) != NULL)
        {
            printf( "Found %c in position %d,%s\n", found_name, i+1, name[i]);
            printf( " index of player is %d.\n",i +1);
        }
    }
    return 0;
}

2 Answers 2

2

You need to make found_name a char array, not char. Also, you need to search using strstr (search for string), not strchr (search for single character).

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define PEOPLE 4
#define LEN_NAME 30
int main(void)
{
    int i;
    char found_name[LEN_NAME];
    char name[PEOPLE][LEN_NAME] = { "John Lucas", "Armanod Jonas",
    "Jack Richard", "Donovan Truck"
    };

    printf("What name do you want to search?\n>");
    scanf("%29s", found_name);
    for (i = 0; i < PEOPLE; i++) {
    if (strstr(name[i], found_name) != NULL) {
        printf("Found %c in position %d,%s\n", found_name, i + 1,
           name[i]);
        printf(" index of player is %d.\n", i + 1);
    }
    }
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

That was it buddy, Thank you very much . Now , do you know how to pass only this index into a function: like i have some values: score [PEOPLE]={ 23,12,45,12}; and i create a function where i find the smallest, and then I want to display only the score for this index i found ( from search ) and the position of that person. do you have any idea anything would help me thank you , appreciate it
int smallest(int a[], int n) { int i,m=a[0]; for(i=1; i<n; i++) if(a[i]<m) m=a[i]; return m; }
0

Found_name is only a character when it should be a char *with the correct amount of space. So if you type in "Find this string", how could you store that string into a 1 byte location?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.