Reputation: 441
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;
}
Upvotes: 0
Views: 14688
Reputation: 2930
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;
}
Upvotes: 2
Reputation: 2852
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?
Upvotes: 0