0

我刚从C开始。我写了一些非常基本的练习代码,它应该将键盘输入读入一个数组,输出最长行的长度然后打印它。有一个读取输入的函数,我希望它打印出每个字符,因为它每次都分配给数组,但它不起作用。它打印了一些看起来很奇怪的字符。我确实在寻找“数组打印垃圾”。但没有找到答案。

    int getline(char line[])
    /*
    This function   1) Reads a line of input until a '\n',
                    2) Returns the length of the line and
                    3) Saves the line in the array "line[]"
    */
    {
        int c,i;
        i=0; // The character count
        printf("Enter characters:\n");

        while((c=getchar())!='\n') // Reads input until it hits a '\n'
        {
            line[i]=c;
            i++;
            printf("char %d = %c \n ",i,line[i]);// 

为什么这个“printf”不能正常工作?它在第二个占位符处打印一个奇怪的字符

        }
        printf("you typed %d characters.\n",i); //Outputs the number of characters typed

        return i;
    }
4

1 回答 1

1

你在增加line[i] i打印。所以你总是在你刚刚设置的元素之后打印元素,这通常是垃圾。

放线

i++;

while循环结束时。

于 2013-06-09T11:55:51.773 回答