2015-04-03 101 views
0

我想写一个程序,可以搜索文件中的字符串(称为student.txt)。我希望我的程序在文件中找到相同的单词时打印该单词,但它显示错误。在c中的文件中搜索字符串

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(int argc, char const *argv[]) 
{ 
int num =0; 
char word[2000]; 
char *string[50]; 

FILE *in_file = fopen("student.txt", "r"); 
//FILE *out_file = fopen("output.txt", "w"); 

if (in_file == NULL) 
{ 
    printf("Error file missing\n"); 
    exit(-1); 
} 

while(student[0]!= '0') 
{ 
    printf("please enter a word(enter 0 to end)\n"); 
    scanf("%s", student); 


    while(!feof(in_file)) 
    { 
     fscanf(in_file,"%s", string); 
     if(!strcmp(string, student))==0//if match found 
     num++; 
    } 
    printf("we found the word %s in the file %d times\n",word,num); 
    num = 0; 
} 

return 0; 
} 
+0

如果(!STRCMP(字符串,学生))== 0应该如果(!STRCMP(字符串,学生)== 0) – Anshul 2015-04-03 09:32:43

+0

仍然得到错误 – jimo 2015-04-03 10:17:38

+0

你得到什么样的错误被替换究竟? – mushfek0001 2015-04-03 11:08:20

回答

-1

无论是在过去的printf()行中使用变量student或将您的匹配文本中的变量word,并检查您是否条件。

0

以最简单的形式添加了示例代码。照顾任何角落案件。 如果您正在搜索字符串“to”。并且文件内容如下:

<tom took two tomatoes to make a curry> . 

输出结果为5.但实际上只有一个单词“to”。

代码:

#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 

int main(int argc, char const *argv[]) 
{ 
     int num =0; 
     char word[2000]; 
     char string[50]; 
     char student[100] = {0}; 

     while(student[0]!= '0') 
     { 
       FILE *in_file = fopen("student.txt", "r"); 
       if (in_file == NULL) 
       { 
         printf("Error file missing\n"); 
         exit(-1); 
       } 

       printf("please enter a word(enter 0 to end)\n"); 
       scanf("%s", student); 
       while (fscanf(in_file,"%s", string) == 1) 
       { 
         //Add a for loop till strstr(string, student) does-not returns null. 
         if(strstr(string, student)!=0) {//if match found 
           num++; 
         } 
       } 
       printf("we found the word %s in the file %d times\n",student,num); 
       num = 0; 
       fclose(in_file); 
     } 
     return 0; 
} 

由于正确我的同事,我们需要有一个更加循环遍历了相同的单词在同一行任何进一步的实例说。

注意:在情况下,如果你想的话“到”只进行计数,请务必检查的“串 - 1”和“字符串+ 1”的字符所有可能的单词分隔符像空格,逗号,句号,换行符,感叹号,符号,等号和任何其他可能性。一种简单的方法是使用strtok,它会根据参数中指定的分隔符将缓冲区标记为单词。签出如何使用strtok。

http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

+0

谢谢,但对不起,在这里混淆的东西,我正在寻找这个词。就像你提到的例子,我希望我的程序能找到并打印'to'。 – jimo 2015-04-04 15:45:53

+0

您一定需要使用'strtok',或者用其他方式解析这些单词。正如所写,您的代码每行只计算一次事件。 – 2015-04-07 20:49:02