【问题标题】:Reading input into an array using getchar() in c在 c 中使用 getchar() 将输入读入数组
【发布时间】:2016-02-18 02:59:20
【问题描述】:

我正在编写一个函数来读取字符输入,它必须在开始处理输入行的其余部分之前消耗前导空格。我成功读取了输入的前导空白字符(如果存在)。但是对于我的一生,当我尝试阅读其余部分时,我无法弄清楚何时会出现段错误。我正在使用 ansi C。这是我的代码:

    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;

谢谢!

【问题讨论】:

  • 请注意,您丢弃了第一个(可能只有)非空白字符。您还需要测试 EOF(您正在使用 int c; 这很好 - 它允许您可靠地测试 EOF)。您可能想查看&lt;ctype.h&gt;isspace()isblank()

标签: c struct io getchar


【解决方案1】:

即使对于您丢弃的字符,您也在增加 index,因此您很可能正在注销数组的末尾。

您可能还希望 while(c != '\n') { 成为 while(index &lt; 35 &amp;&amp; c != '\n') { - 根据您是否需要 0 终止字符串,根据需要进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多