這是賦值的一部分,因此說明很明確,我不允許使用除指定內容以外的任何內容。使用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函數。
我已經給了一個測試文件來運行,它只是告訴我,我沒有產生正確的輸出。 我真的不能看到輸出找出什麼是錯的
我是新來的指針,所以我期待這是我的一個簡單的錯誤。我的程序在哪裏出錯?
請包括輸入文件的內容,您的輸出和預期輸出。 –
什麼是「Entry」? –
如果您在獲取輸出時遇到問題,那麼我建議您提供一個[最小完整可驗證的示例](http://stackoverflow.com/help/mcve)作爲一個新問題,並詢問「爲什麼可以我看到這個結果了嗎?「 – daphtdazz