2016-08-05 76 views
0

我試圖在C中編寫一個程序來打印通過getchar()輸入的單詞的長度。以下是代碼:來自getchar()的單詞的長度

#include<stdio.h> 

#define IN 1 
#define OUT 0 

int main() 
{ 
int c, chars, state, i; 
int nlength[20]; 

state = OUT; 
chars = 0; 

for (i = 0; i < 20; ++i){ 
    nlength[i] = 0; 
} 


while ((c = getchar()) != EOF){ 
    if (c != ' ' && c != '\t' && c != '\n'){ 
     state = IN; 
     ++chars; 
    } 

    else if (state == OUT){ 
      ++nlength[chars]; 
      chars = 0; 
    } 
} 
if (c == EOF){ 
    ++nlength[chars]; 
} 

printf("\nLength of words = "); 

for (i = 0; i < 20; ++i){ 
    printf(" %d", nlength[i]); 
} 

printf("\n"); 
} 

對於「aaa aaa」輸入的示例,應該輸出:0 0 0 2 0 0 0 ...。 但是,它輸出類似於0 0 0 0 0 0 1 0 0 ...。誰能告訴我它有什麼問題?

+4

這是使用調試器來跟蹤代碼,看看究竟怎麼回事的絕佳機會。這樣做,很有趣! :-) – alk

+0

@someuser你是什麼意思 – smudge49

+0

首先,你爲什麼需要狀態變量,如果你不使用它?其次,你不增加當前單詞的長度,而是增加數組中的單詞索引。 – someuser

回答

1

在你的代碼state永遠不會改變OUT,所以下面幾行:

else if (state == OUT){ 
     ++nlength[chars]; 
     chars = 0; 
} 

永遠不會執行。

還有幾個地方看起來很可疑。例如。你從不檢查數組邊界。你也不需要一個state變量,你可以檢查是否chars > 0

這裏是你的代碼有一些修改:

#include <stdio.h> 
// we can use isspace function from ctype.h 
#include <ctype.h> 

#define MAX_LEN 20 

int main() { 
    int c; 
    int chars = 0; 
    // this way we don't have to zero the array explicitly 
    int nlength[MAX_LEN] = {0}; 

    while ((c = getchar()) != EOF) { 
    if (!isspace(c)) 
     ++chars; 
    else { 
     // if chars == 0 we increment nlength[0] 
     // which is not used anyway 
     if (chars < MAX_LEN) 
     ++nlength[chars]; 
     chars = 0; 
    } 
    } 

    // if chars == 0 we increment nlength[0] 
    if (chars < MAX_LEN) 
    ++nlength[chars]; 

    // set 0-length words element to zero 
    nlength[0] = 0; 

    printf("\nLength of words = "); 

    for (int i = 0; i < MAX_LEN; ++i) { 
    printf(" %d", nlength[i]); 
    } 

    printf("\n"); 
} 
+0

@lakov Davydov非常感謝你,它確實清除了一切。 – smudge49