I have written a small code which is supposed to read the console input line and give out the total line number. It gives correct output sometimes & wrong sometimes. It's usually wrong if 1 line contains only 1 char like:
a
b
c
d
There is some mistake but I'm not able to catch what it is. I have tried various combinations of the code, debugging & asking someone else (not this community) to have a look and help me. But all have failed till now. If anyone can point out where I am wrong and what will work, I'll be very grateful.
Here is the code:
#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;
}
thank you in advance
CodePudding user response:
You call your 'next_line' function twice in the 'read' function, therefore you only count every second line. As others have pointed out feof() is unreliable in this usecase. Consider the following revision of your code:
#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;
}