2015-04-03 28 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