[英]strncmp gives 0 even when strings are NOT equal - C
我在strncmp
中遇到 strncmp function 的情况,即使单词不匹配,它也会返回 0,在下面的示例中,我正在用字母“R”测试它,运行代码时它返回 0,即使比较txt 文档中的单词是“RUN”。 你是否碰巧知道
我是否在 strncmp function 或我的代码中的其他地方遗漏了什么?
谢谢您的意见。
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] = '\0';
// Modify this:
// int result = strncmp(wordindic, wordtosearch, lenwordtosearch);
int result = strcmp(wordindic, wordtosearch);
问题是它将 R 与 RUN 进行比较,结果为 0。我希望它仅在找到 R 时返回 0。
在这种情况下,您需要使用 function strcmp
比较整个单词,而不是使用 function strncmp
仅比较lenwordtosearch
字符。
考虑到 function fgets
可以 append 换行符'\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);
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.