簡體   English   中英

在C中使用getchar()將輸入讀入數組

[英]Reading input into an array using getchar() in c

我正在編寫一個函數來讀取字符輸入,該字符必須在開始處理輸入行的其余部分之前先消耗空格。 我成功讀取了輸入的前導空白字符(如果存在)。 但是對於我一生來說,當我嘗試閱讀其余部分時,我無法弄清何時出現段錯誤。 我正在使用ansiC。這是我的代碼:

    void readCharLine(char **line_address) {
        int c;
        int index = 0;
        *line_address = malloc(35 * sizeof(char));
        c = getchar();

        /*Consume white spaces*/
        while ((c == ' ') && (index < 35)) {
            c = getchar();
            index++;
        }

        c = getchar();

        /*read rest of line*/
        while(c != '\n') {  
            *line_address[index] = c;
            c = getchar();
            index++;
        }
    }

我將readCharLine稱為如下:

    readCharLine(&node -> input);

其中node是聲明為以下內容的結構:

    /*Node declaration*/
    typedef struct {
        char *input;
        struct Node *next;
    } Node;

謝謝!

即使對於丟棄的字符,您的index也會遞增,因此您有可能注銷數組的末尾。

您可能還希望while(c != '\\n') {while(index < 35 && c != '\\n') { -根據是否需要終止0來根據需要進行調整。

暫無
暫無

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

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