首页 > 解决方案 > 即使字符串不相等,strncmp 也会给出 0 - C

问题描述

strncmp在 C 中遇到函数的情况,即使单词不匹配,它也会返回 0,在下面的示例中,我正在使用字母“R”对其进行测试,并且在运行代码时,即使比较的单词也返回 0在 txt 文档中是 'RUN'。你碰巧知道是否

我是否遗漏了 strncmp 函数中的某些内容或代码中的其他地方?

谢谢您的意见。


bool lookup(string s);

int main(void) {

char *s;
s = "R";
if (lookup(s)) {
    printf("Word found =)\n");
} else {
    printf("Word not found =(\n");
}
}

// Looks up word, s, in txt document.
bool lookup(string s)
{
 // TODO
    char *wordtosearch;
    wordtosearch = s;
    int lenwordtosearch = strlen(wordtosearch);
    char arraywordindic[50];

// Open txt file
FILE *file = fopen("text.txt", "r");
if (file == NULL)
{
    printf("Cannot open file, please try again...\n");
    return false;
}

while (!feof(file)) {
    if (fgets(arraywordindic, 50, file) != NULL) {
        char *wordindic;
        wordindic = arraywordindic;
        int result = strncmp(wordindic, wordtosearch, lenwordtosearch);
        if (result == 0) {
            printf("%i\n", result);
            printf("%s\n", wordindic);
            printf("%s\n", wordtosearch);
            fclose(file);
            return true;
        }
    }        
}
fclose(file);
return false;
}

标签: cfgetsc-stringsstrcmpstrncmp

解决方案


int result = strncmp(wordindic, wordtosearch, lenwordtosearch);

如果 的第一个字符与字典中任何单词的第一个lenwordtosearch字符wordtosearch匹配,这将为您提供零。lenwordtosearch

鉴于您要搜索的单词是,字典中以开头S任何单词都会为您提供匹配项。S

您可能应该检查整个单词。这可能意味着清理您从文件中读入的单词(即删除换行符)并使用strcmp()类似的东西:

wordindic = arraywordindic;

// Add this:
size_t sz = strlen(wordindic);
if (sz > 0 && wordindic[sz - 1] == '\n')
    wordindic[sz - 1] = '\0';

// Modify this:
// int result = strncmp(wordindic, wordtosearch, lenwordtosearch);
int result = strcmp(wordindic, wordtosearch);

推荐阅读