簡體   English   中英

奇特的結果。 #1-13 C 編程語言書

[英]Peculiar results. #1-13 The C Programming Language Book

K&R 的“C 編程語言”一書中的問題 1-13 要求讀者創建一個程序,該程序將按長度制作單詞的直方圖。 這些詞將由用戶輸入。

我嘗試創建一個程序,該程序將存儲每個長度的單詞數量,然后在處理直方圖之前打印出每個數組塊的 int 值。 無論我如何擺弄這個程序,它總會給我兩個結果之一; 要么是“1”,要么是我假設的數組地址? “6422476”。 為什么會這樣?

#include <stdio.h>
#define GREATEST 10

int main(void){
    int c, word=0;
    int word_count[GREATEST];

    /*set all values in word_count to 0*/
    for(int i=0; i<GREATEST; i++){
        word_count[i]=0;
    }

    while((c=getchar()) != EOF){
        if(c != ' '){
            ++word;
        } else{
            word_count[word-1]=+1;
            word=0;
       }
    }

    for(int j=0; j<GREATEST; j++){
        printf("\n%d", word_count[j]);
    }
    return 0;
}

你總是得到 1 是有充分理由的。請注意

word_count[word-1]=+1; // This assigns to the value "+1"!`

應該

word_count[word-1]+=1; // This increments your array item`

在 C 中編譯的東西很麻煩:)。

我使用正確的+=或“不正確” =+運行您的代碼,並且都給出了相同的輸出:

a bb bb ccc ccc ccc dddd dddd dddd dddd qwertyuiop eeeee

1 2 3 4 0 0 0 0 0 1

a bb bb ccc ccc ccc dddd dddd dddd dddd qwertyuiop eeeee

1 2 3 4 0 0 0 0 0 1

但是,兩者都刪除了輸入的最后一個單詞 - 5 個字符長度的單詞為零。 我認為這是因為您在EOF上退出 while 循環,例如ctrl + D並且未處理自最后一個空格' '以來輸入的任何內容。

此外,如果用戶在多於一行上輸入“單詞”或由空格分隔的“單詞”組,則結果不正確。 這些用於輸入單詞的“選項”使一致地處理輸入變得更加困難。

您最好指示用戶一次輸入一個單詞並拒絕包含空格的輸入。 這使得控制輸入和處理所有輸入的單詞變得更加容易。

這是使用緩沖區保存輸入的輸入代碼片段。 緩沖區大小、直方圖數組和最大允許字長都是使用靜態變量maxlen

/* tell user what to enter */
printf("Type one word at a time (hit enter after each word)\nType 99 to finish\n");

/* get lines of input */
while ((fgets(buff, maxlen ,stdin)) != NULL) {
    /* test for '99' end code */
    if(strncmp(buff, "99", 2) == 0) break;
    /* test for any spaces in input -if so ignore input & print message */
    if(strstr(buff, " ") != NULL ) {
        printf("Enter one word at a time - then hit enter\n");
        } else {
        /* else get size of word (-1 for newline)  & increment appropriate counter */
        length = strlen(buff) - 1;
        hist[length]++;
    }
 }

緩沖區是這樣設置的

char *buff = malloc(maxlen + 1);

並且必須在輸入完成后釋放

free(buff);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM