2013-03-19 2 views
1

현재 각 고유 단어를 찾아 파일에 단어가 나타나는 횟수를 세는 프로그램을 만들려고합니다. 내가 현재 사용자에게 단어를 물어보고 단어가 나타나는 횟수를 파일에서 검색합니다. 그러나 사용자에게 개별 단어를 묻는 대신 파일을 읽는 프로그램이 필요합니다. 파일에서 단어를 읽고 파일에서 해당 단어를 읽는 프로그램

내가 현재 가지고있는 것입니다 :

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

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

FILE *in_file = fopen("words.txt", "r"); 

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

scanf("%s",word); 

printf("%s\n", word); 

while(!feof(in_file))//this loop searches the for the current word 
{ 
    fscanf(in_file,"%s",string); 
    if(!strcmp(string,word))//if match found increment num 
    num++; 
} 
printf("we found the word %s in the file %d times\n",word,num); 
return 0; 
} 

난 그냥 (아직가 확인되지 않은 단어) 고유 한 단어 파일을 읽는 방법을 알아내는 도움이 필요하지만 내 프로그램에 대한 다른 제안 감사하겠습니다.

+0

당신은 당신이 본 한 단어의 테이블과 몇 번을 본 적이을 유지해야합니다. C는 이러한 메커니즘을 제공하지 않으므로 직접 만들거나 라이브러리를 사용해야하지만 트리 또는 해시 테이블과 같은 것이 적절할 수 있습니다. – FatalError

+0

제쳐두고,'feof()'를 사용하지 마라. 대신에'fscanf()'의 결과를 확인해야한다. –

답변

1

파일에 포함 된 모든 줄을 한 번만 인쇄하려면 주어진 데이터 구조에서 읽은 문자열을 저장해야합니다. 예를 들어, 정렬 된 배열이 트릭을 수행 할 수 있습니다. 코드는 다음과 같을 수 있습니다

#include <stddef.h> 

size_t numberOfLine = getNumberOfLine (file); 
char **previousStrings = allocArray (numberOfLine, maxStringSize); 
size_t i; 

for (i = 0; i < numberOfLine; i++) 
{ 
    char *currentString = readNextLine (file); 

    if (!containString (previousStrings, currentString)) 
    { 
     printString (currentString); 
     insertString (previousStrings, currentString); 
    } 
} 

당신은 효율적인 방법으로 기능 containStringinsertString를 코딩 이진 검색을 사용할 수 있습니다. 자세한 내용은 here을 참조하십시오.

1

코드를 함수 (서브 루틴)로 분할해야합니다.

하나의 함수는 파일을 읽고 모든 단어를 기록합니다. 다른 하나는 각 단어의 발생 횟수를 계산합니다.

int main(int argc, char const *argv[]) 
{ 
    char *words[2000]; 

    // Read the file; store all words in the list 
    int number_of_words = ReadWords("words.txt", words, 2000); 

    // Now count and print the number of occurrences for each word 
    for (int i = 0; i < number_of_words; i++) 
    { 
     int n = CountOccurrences(words[i], "words.txt"); 
     printf("we found the word %s in the file %d times\n", words[i], n); 
    } 

    // Deallocate dynamically allocated memory 
    Cleanup(words, number_of_words); 
} 

기능이 비교적 짧다는 점에 유의하십시오. 모든 세부 사항은 ReadWordsCountOccurrences에 있습니다.

는 파일에서 모든 단어를 읽고 구현하려면 :

int ReadWords(const char *filename, char *words[], int max_number_of_words) 
{ 
    FILE *f = fopen(filename, "rt"); // checking for NULL is boring; i omit it 
    int i; 
    char temp[100]; // assuming the words cannot be too long 

    for (i = 0; i < max_number_of_words; ++i) 
    { 
     // Read a word from the file 
     if (fscanf(f, "%s", temp) != 1) 
      break; 
     // note: "!=1" checks for end-of-file; using feof for that is usually a bug 

     // Allocate memory for the word, because temp is too temporary 
     words[i] = strdup(temp); 
    } 
    fclose(f); 

    // The result of this function is the number of words in the file 
    return i; 
} 
+0

3 년 전부터 알고 있지만 fscanf (...)! = 1과 fscanf (...)의 차이점은 무엇입니까? = EOF? – Naman

+0

1과 비교하면 파일 끝에 대한 입력뿐만 아니라 구문 오류도 검사합니다. 설명 : http://en.cppreference.com/w/c/io/fscanf – anatolyg

0
`#include <stdio.h> 
#include <stdlib.h> 

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

FILE *in_file = fopen(argv[1], "r"); 

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

scanf("%s",word); 

printf("%s\n", word); 

while(!feof(in_file))//this loop searches the for the current word 
{ 
    fscanf(in_file,"%s",string); 
    if(!strcmp(string,word))//if match found increment num 
    num++; 
} 
printf("we found the word %s in the file %d times\n",word,num); 
return 0; 
}` 

if any suggestion plz..most welcome 

Blockquote 
+1

이 코드는 문제를 해결하는 데 도움이 될 수 있지만 _why_ 및/또는 _how_가 질문에 대답하는 것을 설명하지 않습니다. 이러한 추가적인 맥락을 제공하면 장기적인 교육적 가치가 크게 향상 될 것입니다. 어떤 제한 사항과 가정이 적용되는지를 포함하여 설명을 추가하려면 답을 [편집하십시오]. –

관련 문제