2016-12-01 93 views
0

我已经写下了下面的代码,但是strcmp函数工作不正常。它不从文本文件中提取已知文本,并返回0作为单词计数。C语言不能让Strcmp工作

int count = 0; 
char line[400]; 
char word[20]; 

printf("Search for? \n"); 
scanf_s("%s", word, 19); 

if (Fp == NULL) 
{ 
    printf("File not found"); 
} 
while (!feof(Fp)) 
{ 
    fgets(line, 150, Fp); 

    if (strcmp(line, word) == 0) //searches the line to find word 
    { 
     count++;//increment 
    } 
} 

printf("Search returned %s was found %d number of times", word, count); 
+4

注意'line'包含一个换行符。并阅读[为什么是“while(!feof(file))”总是错?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – BLUEPIXY

回答

1

那么,strcmp()不会做你可能会认为它。你的代码注释说它搜索行中的单词;这是不正确的。 strcmp只是说明你传递给它的两个字符串是否相同(或者,如果不是这样的话,哪一个会首先出现)。

+0

现在有道理,谢谢 – Zimmer

3

不要使用STRCMP(),试试这个来代替:

if (strstr(line, word)) { ... } 
+0

感谢这工作 – Zimmer