2017-02-24 86 views
0

這是賦值的一部分,因此說明很明確,我不允許使用除指定內容以外的任何內容。使用fgets和strstr對C中的字符串進行計數

的思想很簡單:

1)創建其保持的字符串和一個計數

2)計數在每個結構中的字符串的出現,並存儲計在結構

結構的數組

3)打印字符串及其出現次數

我已經明確告訴使用fgets和功能的strstr

這裏是我這麼遠,

#define MAX_STRINGS 50 
#define LINE_MAX_CHARS 1000 
int main(){ 
    int n = argc - 1; 
    if (n > MAX_STRINGS) { 
    n = MAX_STRINGS; 
    } 
    Entry entries[MAX_STRINGS]; 
    char **strings = argv+1; 
    prepare_table(n, strings, entries); 
    count_occurrences(n, stdin, entries); 
    print_occurrences(n, entries); 
} 

void prepare_table (int n, char **strings, Entry *entries) { 
    // n = number of words to find 
    // entries = array of Entry structs 
    for (int i = 0; i < n; i++){ 
     Entry newEntry; 
     newEntry.string = *(strings + 1); 
     newEntry.count = 0; 
     *(entries + i) = newEntry; 
    } 
} 

void print_occurrences (int n, Entry *entries) { 
    for (int i = 0; i < n; i++){ 
     printf("%s: %d\n", (*(entries + i)).string, (*(entries + i)).count); 
    } 
} 

void count_occurrences (int n, FILE *file, Entry *entries) { 
    char *str; 
    while (fgets(str, LINE_MAX_CHARS, file) != NULL){ 
     for (int i = 0; i < n; i++){ // for each word 
      char *found; 
      found = (strstr(str, (*(entries + i)).string)); // search line 
      if (found != NULL){ // if word found in line 
      str = found + 1; // move string pointer forward for next iteration 
      i--; // to look for same word in the rest of the line 
      (*(entries + i)).count = (*(entries + i)).count + 1; // increment occurrences of word 
      } 
     } 
    } 
} 

我知道一個事實,我的prepare_table和print_occurrences功能都完美的工作。但是,問題在於count_occurrences函數。

我已經給了一個測試文件來運行,它只是告訴我,我沒有產生正確的輸出。 我真的不能看到輸出找出什麼是錯的

我是新來的指針,所以我期待這是我的一個簡單的錯誤。我的程序在哪裏出錯?

+2

請包括輸入文件的內容,您的輸出和預期輸出。 –

+0

什麼是「Entry」? –

+1

如果您在獲取輸出時遇到問題,那麼我建議您提供一個[最小完整可驗證的示例](http://stackoverflow.com/help/mcve)作爲一個新問題,並詢問「爲什麼可以我看到這個結果了嗎?「 – daphtdazz

回答

1

fgets(char * restrict str, int size, FILE * restrict stream)寫入緩衝區str ......但您沒有在str緩衝區。什麼是str?這只是一個指針。它指的是什麼?垃圾,因爲你還沒有初始化它。所以它可能工作,否則它可能不會(編輯:我的意思是你應該期望它不工作,並且如果它確實感到驚訝,謝謝你的評論者!)。

你可以解決這個問題,首先分配一些內存:

char *str = malloc(LINE_MAX_CHARS); 
// do your stuff 
free(str); 
str = NULL; 

甚至靜態分配:

char str[LINE_MAX_CHARS]; 

這是一個問題,我可以看到反正。你說你沒有輸出,但是肯定你至少可以使用fprintf(stderr, "")添加一些調試語句..?

+0

_因此它可能工作,或者它可能不工作。很好,它不太可能工作。 –

+0

因此它可能工作或者它可能不會。嚴格定義短語 - 它不起作用 – KevinDTimm

相關問題