即使字符串不相等,strncmp 也会返回 0 - C

strncmp gives 0 even when strings are NOT equal - C

我遇到了 C 中 strncmp 函数的情况,即使单词不匹配,它也返回 0,在下面的示例中,我用字母 'R' 和当 运行 代码 returns 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;
}
int result = strncmp(wordindic, wordtosearch, lenwordtosearch);

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

鉴于您要搜索的词是 S,字典中任何 开头 S 的词都会给您一个匹配。

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

wordindic = arraywordindic;

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

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

The thing is that it compares R with RUN and it gives 0. I want it to return 0 when it finds R only.

在这种情况下,您需要使用函数 strcmp 比较整个单词,而不是使用函数 strncmp.

只比较 lenwordtosearch 个字符

考虑到函数 fgets 可以将换行符 '\n' 添加到输入的字符串中。您需要在比较字符串之前将其删除。

if (fgets(arraywordindic, 50, file) != NULL) {
    arraywordindic[ strcspn( arraywordindic, "\n" ) ] = '[=10=]';
    int result = strcmp(arraywordindic, wordtosearch);
    if (result == 0) {
        printf("%i\n", result);
        printf("%s\n", arraywordindic);
        printf("%s\n", wordtosearch);

因此这些声明

int lenwordtosearch = strlen(wordtosearch);

char *wordindic;
wordindic = arraywordindic

可能会被删除。

而while循环的条件应该这样写

while ( fgets(arraywordindic, 50, file) != NULL ) {
    arraywordindic[ strcspn( arraywordindic, "\n" ) ] = '[=13=]';
    int result = strcmp(arraywordindic, wordtosearch);
    if (result == 0) {
        printf("%i\n", result);
        printf("%s\n", arraywordindic);
        printf("%s\n", wordtosearch);
    //...