c - 使用 getchar() 获取一行时出现无限循环

标签 c kernighan-and-ritchie

我正在尝试 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/

相关文章:

c - 在目录的每个文件中追加一行

带有 syslog 日志记录的 C 宏

c - K 和 R 练习 1-24

c - 为什么编译 K&R2 第 1 章的最长行示例时会出现 "conflicting types for getline"错误?

c - 在 C 中使用寄存器变量的一个很好的例子是什么?

c - 无符号整数中的填充位和 C89 中的按位运算

c - 如何在 Objective-C 的结构中将 NSString 的值存储为 char 数组?

c - 有没有办法将没有显式命名类型的结构作为参数传递给函数?

c - 更好地理解 printf - 当提供的值为负时,它用 "%c"打印什么?

计算 C 中空格、制表符的数量