我刚刚开始使用 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;
}
最佳答案
在增加 i
后,您将打印 line[i]
。因此,您总是在刚刚设置的元素之后打印元素,这通常是垃圾。
放线
i++;
在 while
循环的末尾。
关于c - 为什么数组的元素打印不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17009303/