首页 > 解决方案 > C 线性搜索无法使用 strcmp 比较两个字符串,编译正常

问题描述

程序运行并退出,代码为 0,但没有输出,它应该是一个线性搜索程序

我查看了其他类似的问题,我尝试用 \n 结束数组。尝试而不是仅仅依靠“if(strcmp = 0)”来制作具有strcmp返回值的东西,我很新,而且我正在学习的东西不是很好,只是让事情变得最糟糕,我试着看看如果是关于 strcmp 期望的 char* 值,但找不到问题

#include <stdio.h>
#include <string.h>
#define max 15

int lineal(char elementos[], char elebus)
{
    int i = 0;
    for(i=0; i<max; i++)
    {
        if(strcmp(elementos[i], elebus)==0)
        {
        printf("Elemento encontrado en %d,", i); //element found in
        }
    else 
        {
        printf("elemento no encontrado"); //not found
        }
    }

}

int main()
{
    char elebus[50];
    char elementos[max][50]= {"Panque", "Pastel", "Gelatina", "Leche", "Totis", "Tamarindo" "Papas", "Duraznos", "Cacahuates", "Flan", "Pan", "Yogurt", "Café", "Donas", "Waffles"};
    printf("Escribir elemento a buscar\n");
    scanf("%s", elebus);

    int lineal(char elementos[], char elebus);
}

预期的输出将是在“i”位置找到的元素,如果找到则打印“未找到”

标签: cstringsearchstrcmp

解决方案


你想给它传递一个字符串来查找,而不仅仅是一个字符,而且,elementos应该是一个二维数组。将函数的签名更改为:

int lineal(char elementos[max][50], char *elebus)

Also, in main, you don't call the function. Instead, you just declare it again. call it like this:

lineal(elementos, elebus);

Furthermore, I would change it to return void instead of int. You're neither returning anything (that's undefined behavior) nor are you using the return value anywhere. But I assume that this isn't the final version and you want to return the index at some point.


On a side note, right now it's printing that it didn't find the element for every time it didn't match, even if it does find it eventually. I would recommend this instead:

for (i = 0; i < max; i++)
    {
        if (strcmp(elementos[i], elebus) == 0)
        {
            printf("Elemento encontrado en %d\n,", i); //element found in
            return;
        }
    }
    printf("elemento no encontrado\n"); //not found

This is printing "elemento no encontrado" only once, and only when the string wasn't found.


推荐阅读