2013-10-08 2 views
1

편집 : 코드에서 수정 된 오류가 수정되었습니다. 표준 입력에서 읽는 단어 빈도 해석 프로그램을 만들려고했습니다. 두 가지 질문이 있습니다.C : 링크 된 목록 단어 빈도 - 표준 입력

  1. 현재 '\ n'을 사용하여 프로그램에서 입력을 읽을 때를 중지해야하는 경우 사용자가 입력을 마칠 때까지 읽어야합니다. EOF 나 널 터미네이터 '\ 0'을 사용하는 것이 더 낫지 만
  2. 이것은 바보 같은 질문 일 수 있습니다. 그러나 매번 글자가 두 배가되는 출력물에 어떤 문제가 있는지 알 수 없습니다.

예시 입력 "이 주파수에 대한 프로그램의 테스트 테스트되고있는 이것을위한"출력이

: 만약 카운트시피

thhiiss 1 
iiss 2 
aa 2 
tteesstt 2 
ooff 1 
tthhee 1 
pprrooggrraamm 1 
ffoorr 3 
ffrreeqquueennccyy 1 
tthhiiss 1 

근접 각각 보정하기 그러나 글자가 중복되는 이유를 알아낼 수는 없습니다. 는 여기에 내가 사용한 코드 :

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

#define MAXWORD 100 

//=========================================================================== 
struct lnode { 
    struct lnode *next; 
    struct lnode *counter; 
    struct lnode *pLast; 
    struct lnode *prev; 
    struct lnode *head; 
    char *word; 
    int line; 
    int count; 
    int freq; 
}; 

struct lnode *start = NULL; 

//=========================================================================== 
struct lnode *createWordCounter(char *str) 
    { 
    struct lnode *pCounter = NULL; 
    pCounter = (struct lnode*)malloc(sizeof(struct lnode)); 
    pCounter->word = (char*)malloc(strlen(str)+1); 
    strcpy(pCounter->word, str); 
    pCounter->freq = 1; 
    pCounter->next = NULL; 
    return pCounter; 
    } 
//=========================================================================== 
void addWord(char *str) 
{ 
    struct lnode *pCounter = NULL; 
    struct lnode *pLast = NULL; 

    if(start == NULL) 
    { 
    start = createWordCounter(str); 
    return; 
    } 
    // If the word is in the list, increment its count 
    pCounter = start; 
    int temp = pCounter->freq; 
    while(pCounter != NULL) 
    { 
    if(strcmp(str, pCounter->word) == 0) 
    { 
     pCounter->freq++; 
     return; 
    } 
    pLast = pCounter;    
    pCounter = pCounter->next; 
    } 

    // Word is not in the list, add it 
    pLast->next = createWordCounter(str); 
} 
//=========================================================================== 
int getNextWord(char *buf, int bufsize) { 
    char *p = buf; 
    char ch; 
    do { 
     ch = getchar(); 
     if (ch == '\n') 
      return 0; 
     } while (!((ch >= 'A' && ch <= 'Z')||(ch >= 'a' && ch <= 'z'))); 
    do { 
     if (p - buf < bufsize - 1){ 
      if(ch >= 97 && ch <= 122)//making the ch lowercase if needed 
        *p++ = ch; 
      else{ch += 32; 
        *p++ = ch;} 
       }//End of if 
     ch = getchar(); 
     } while (((ch >= 'A' && ch <= 'Z')||(ch >= 'a' && ch <= 'z'))); 
     *p = '\0'; 
     return 1; 
     } 
//=========================================================================== 
void show(struct lnode *pWord) 
{ 
printf("%s %i\n", pWord->word, pWord->freq); 
} 
//=========================================================================== 

int main(){ 
    struct lnode *counter = NULL; 
    int size = 1000; 
    char buf[MAXWORD]; 
    while(getNextWord(buf, size) != 0){ 
     addWord(buf); 
    } 

    counter = start; 

    while(counter != NULL) 
    { 
     show(counter); 
     counter = counter->next; 
    } 

    counter = start; 

    while(counter != NULL) 
    { 
    free(counter->word); 
    start = counter; 
    counter = counter->next; 
    free(start); 
    } 

return 0; 
} 

이 내 처음 그래서 난 아무 잘못을 한 경우에 알려 주시기 바랍니다 게시됩니다. 어떤 도움을 주셔서 감사합니다.

감사합니다. 이것

+0

단어 수는 실제로 맞습니까? 내게 그렇게 보이지는 않아. – zubergu

+0

가까운 곳에서 글을 편집했지만 처음 두 문제를 먼저 풀려고합니다. 알려 줘서 고마워. – JumpingRock

답변

0
Would it be better to use EOF or the null terminator '\0' ? 

는 사용 EOF가 있기 때문에 ctl+Dgetchar()EOF로 입력을 고려한다. 또한

what is wrong with my output it doubles the letters up every time ? 

EOF이 부분 위의 기능 getNextWord()

if(ch >= 97 && ch <= 122)//making the ch lowercase if needed 
      *p++ = ch; 
     //this checks if input character is lowercase character, then store it into buffer 
    else{ch += 32;} // if input character is lowercase character, won't execute else part 
      *p++ = ch; 
      // now again you are copying same input character into buffer next location 

수정 코드 아래에이를 참조 \n를 사용하거나 \n와 함께 OR 논리를 사용 할 수 있습니다.

+1

감사합니다. 나는 복제 오류를 수정하기 위해 코드를 편집했습니다. 당신의 도움을 주셔서 감사합니다. – JumpingRock

+0

대부분 환영합니다. 네, 문제가 해결되었습니다. 프로그램을 읽기 쉽게하려면 ctype 함수 [Here] (http://en.cppreference.com/w/Main_Page) 및 [Here] (http://www.cplusplus.com/reference/cstdio/sscanf/)를 확인하십시오. – Gangadhar

1

봐 조심스럽게 그것이 내가 *p

 if(ch >= 97 && ch <= 122)//making the ch lowercase if needed 
      *p++ = ch; 
    else{ch += 32;} 
     *p++ = ch; 

에 두 번 else 문에 후행 "}"ch을 생각 할당되는 것은 잘못이다. 이 기능 isalpha, islower, isupper, tolower, toupper에 대해 배울 경우

 if(ch >= 97 && ch <= 122) { //making the ch lowercase if needed 
      *p++ = ch; 
    } else { 
     ch += 32; 
     *p++ = ch; 
    } 

또한, 귀하의 코드는 크게 더 읽을 수 있습니다. 남성용 ctype info. 당신이 누르면

+0

정말 고마워요. 그래, 내가 게시 한 후, 미안해 나는 코딩에 익숙하지 않다는 것을 깨달았다. 나는 정말로 당신의 도움에 감사한다! 나는 그것들을 사용할 수 있다는 것을 알았지 만 이것은 잠시 전에 예정된 실험실을위한 것이었고 우리는 ctype을 사용할 수 없었습니다. – JumpingRock

+0

@ user2856537 인 경우이 대답을 수락 할 수있는 경우 아래쪽 화살표로 체크 표시를 클릭하십시오. 감사. 행운을 빕니다. –