0

如何在二维字符串数组中搜索整个单词。此代码仅输出我输入的单词的第一个字母。

谁能帮我这个 ?

该索引是如何在函数中传递的,只是我从这个搜索中找到的索引。

#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;
}
4

2 回答 2

1

您需要将 found_name 设为 char 数组,而不是 char。此外,您需要使用 strstr(搜索字符串)而不是 strchr(搜索单个字符)进行搜索。

#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;
}
于 2013-06-26T15:11:38.457 回答
0

Found_name 只是一个字符,当它应该是一个具有正确空间量的 char * 时。因此,如果您输入“查找此字符串”,您如何将该字符串存储到一个 1 字节的位置?

于 2013-06-26T15:11:03.687 回答