c - 即使字符串不相等,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;
}
解决方案
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);
推荐阅读
- json - 尝试动态创建 UI/Image 元素并不断更新它们
- python-3.x - 解析有序字典python
- json - SQL Server 2012 中的字符编码问题
- javascript - Javascript 代码未在 Chrome 控制台上执行
- rust - 有没有办法声明一个接受实现 FromStr 的类型作为错误的结果?
- javascript - 为对象数组反应输入 setState
- javascript - 无法获取 req.userData.role 的值
- python - Gimp 程序中的 OpenCV Python 脚本 - 草/硬表面边缘检测
- java - 我需要 java(eclipse) 中的椭圆 ROI 而不是二次 ROI
- java - 创建包含另一个集合的内容加上一个元素的新集合的最快方法是什么