读取控制台然后输出没有。行数

Read console and then output no. of lines

我写了一个小代码,它应该读取控制台输入行并给出总行号。它有时会给出正确的输出,有时会给出错误的输出。如果 1 行仅包含 1 个字符,通常是错误的,例如:
一个
b
c
d
有一些错误,但我无法理解它是什么。我已经尝试了各种代码组合,调试并请其他人(不是这个社区)看看并帮助我。但直到现在都失败了。如果有人能指出我哪里错了,什么地方行得通,我将不胜感激。
这是代码:

#include<stdio.h>
int next_line(){
    int cnt=0;
    int ch;
    ch=getchar();
    while (ch!=EOF)
    {
        ch=getchar();
        cnt ++;
        if (ch ='\n')
        {
            break;
        }
    }
    if ((cnt > 0)||(ch ='\n'))
    {
       return 1;
    }
    else
    {
      return 0;
    } 
}
int read(){
    int lines=0;
    while (!feof(stdin))
    {
        next_line();
        lines += next_line();
    }
    return lines;
}
int main(){
    int n=0;
    n=read();
    printf("\n%d",n);
    return 0;
}

提前致谢

您在 'read' 函数中两次调用了 'next_line' 函数,因此您只计算每一行。正如其他人指出的那样,feof() 在这个用例中是不可靠的。考虑对您的代码进行以下修订:

#include <stdio.h>

int
next_line(void)
{
    int charcount = 0;
    char c;

    while ((c = getchar()) &&
           c != EOF) {
        if (c == '\n') {
            return 1;
        }
        continue;
    }

    return 0;
}

/* renamed from the generic 'read' to avoid naming
   conflicts */
int
count_lines(void) 
{
    int line_count = 0;

    while (next_line()) {
        line_count++;
    }

    return line_count;
}

int
main()
{
    int line_count = 0;
    line_count = count_lines();

    printf("counted %d lines\n", line_count);

    return 0;
}