2013-03-29 23 views
-1
#include <stdio.h> 

int main (void) { 
FILE *fp; 
fp = fopen("test.txt", "r"); 

int char_counter, i, c; 
int word_length[12]; 

char_counter = 0; 
for (i = 0; i <= 12; i++) { 
    word_length[i] = 0; 
} 

while ((c = getc(fp)) != EOF) { 
    if (c == '\n' || c == '\t' || c == ' ') 
    { 
     word_length[char_counter] = word_length[char_counter] + 1; 
     char_counter = 0; 
    } 
    else { 
     ++char_counter; 
    } 
} 

for (i = 0; i <= 12; i++) { 
    printf("%d %d\n", i, word_length[i]); 
} 

return 0; 
} 

的test.txt:直方圖字的長度的調試

blahblahblah blahblah嗒嗒BLA BL BB

輸出:

0 0 
1 1 
2 1 
3 1 
4 1 
5 0 
6 0 
7 0 
8 1 
9 0 
10 0 
11 0 
12 -1 <-- ?? 

預期輸出看起來相同,但有應該是第12行的1而不是-1。我真的不明白我是如何得到一個負數。

+0

你在做KandR練習1-13/1-14嗎? – Sam

+0

哈哈哈,是的,我是! – lche

+0

我已經發布練習1-13。如果你想要,我也會發布練習1-14 – Sam

回答

2

代碼

int word_length[12]; 

意味着你必須在編號爲0的列表12項.. 11

的嘗試訪問項目12你未定義行爲。

+0

感謝您的簡單解釋! – lche

1

看這個snippt:

int word_length[12]; 

char_counter = 0; 
for (i = 0; i <= 12; i++) { 
    word_length[i] = 0; 
} 

你找到的bug?提示:再次檢查號碼12和運營商<=

+0

@ Magtheridon96謝謝。我將修改答案 – 2013-03-29 05:47:39

+0

@ Magtheridon96您是否試圖將其作爲答案發布?哈哈哈!我贏了比賽 – 2013-03-29 05:49:31

+0

@ Magtheridon96我相信他們非常有用:p – 2013-03-29 05:52:02

0

int word_length[12];這意味着它可以存儲最大12 INT數量的,0到11, 所以,word_length[12]沒有得到訪問,因此它給一些垃圾值。

您需要做int word_length[13];並解決您的問題。

+0

謝謝!我現在明白我的錯誤。 – lche

0

Knr的練習1-3

 
#include 

#define TAB_STOP 8 
#define MAX_WORD_TABS 4 
#define MAX_WORD MAX_WORD_TABS * TAB_STOP 

int main() { 

    int c, i, is_first = 1, skip_space = 1, skip_tab = 0; 
    long word_c = 0, word_l = 0; 

    while ((c = getchar()) != EOF) { 
     if (c != ' ' && c != '\t' && c != '\n') { 
      word_l++; 
      skip_space = 0; 
      if (is_first) { 
       ++word_c; 
       is_first = 0; 
      } 
      putchar(c); 
     } else { 
      is_first = 0; 
      if (!skip_space) { 

       if (word_l 0; --word_l) 
        printf("|||||");     //putchar('|'); 

       putchar('\n'); 

       skip_space = 1; 
      } 
     } 
    } 
} 

您可以在UNIX上使用重定向(<,>或>>),用於輸入和程序的輸出...文件的處理是沒有必要的。