1

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

2 回答 2

1
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);
于 2020-08-22T03:34:59.363 回答
1

问题是它将 R 与 RUN 进行比较并给出 0。我希望它仅在找到 R 时返回 0。

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

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

if (fgets(arraywordindic, 50, file) != NULL) {
    arraywordindic[ strcspn( arraywordindic, "\n" ) ] = '\0';
    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" ) ] = '\0';
    int result = strcmp(arraywordindic, wordtosearch);
    if (result == 0) {
        printf("%i\n", result);
        printf("%s\n", arraywordindic);
        printf("%s\n", wordtosearch);
    //...    
于 2020-08-22T03:55:47.273 回答