我正在尝试 K&R(前 1-17)中的练习,并提出了自己的解决方案。 问题是我的程序似乎挂起,可能处于无限循环中。我省略了 NUL ('\0') 字符插入,因为我发现 C 通常会自动将其附加到字符串的末尾(不是吗?)。
有人可以帮我找出问题所在吗?
我正在 win8(x64) 上使用带有 Cygwin 的 GCC 编译器,如果有帮助的话..
问题 - 打印所有长度超过 80 个字符的输入行
#include<stdio.h>
#define MINLEN 80
#define MAXLEN 1000
/* getlin : inputs the string and returns its length */
int getlin(char line[])
{
int c,index;
for(index = 0 ; (c != '\n') && ((c = getchar()) != EOF) && (index < MAXLEN) ; index++)
line[index] = c;
return (index); // Returns length of the input string
}
main()
{
int len;
char chArr[MAXLEN];
while((len = getlin(chArr))>0)
{
/* A printf here,(which I had originally inserted for debugging purposes) Miraculously solves the problem!!*/
if(len>=MINLEN)
printf("\n%s",chArr);
}
return 0;
}
最佳答案
And I omitted the null('\0') character insertion as I find C generally automatically attaches it to the end of a string (Doesn't it?).
不,事实并非如此。您正在使用 getchar()
一次读取一个输入字符。如果您自己将字符放入数组中,则必须自己终止它。
返回字符串的 C 函数通常会终止它,但这不是您在这里所做的。
你的输入循环有点奇怪。逻辑 AND 运算符仅在左侧计算结果为 false 时才执行右侧(称为“短路”)。重新排列循环中测试的顺序应该会有所帮助。
for(index = 0 ; (index < MAXLEN) && ((c = getchar()) != EOF) && (c != '\n'); index++)
line[index] = c;
这样,c
在对内容执行测试之前会从 getchar()
接收一个值。
关于c - 使用 getchar() 获取一行时出现无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629655/