I realized that defining the number of lines actually was a bit trickier than I thought. But after some thinking, I would use this algorithm with pseudo code:
no_lines = 0
while (c=read_character()) != EOF
no_lines++
if c != '\n'
consume_rest_of_line()
I thought of some cases and what size I "wanted" them to have. The cases are shown below.
0 lines: (obvious)
<EOF>
1 line: (obvious)
Hello<EOF>
1 line: (little tricker, feels like 1 line, but it also feels like \n should affect things)
Hello\n<EOF>
1 line: (just HAS to be different than an empty file)
\n<EOF>
2 lines: (just HAS to have one more than the above)
\n
\n<EOF>
2 lines: (ok, i think i have it now)
\n
Hello<EOF>
When I looked at this, I realized that the number of lines is almost the number of \n
but not quite. The \n
only says that it's time to see if there is a next line or not. Any character, including \n
may start a line, but a \n
always ends current line irregardless if it started it or not.
So I ended up with this code:
int main()
{
int c;
size_t no_lines = 0;
while((c = getchar()) != EOF) {
no_lines++;
if(c != '\n')
while(((c = getchar()) != EOF) && c != '\n');
}
printf("%zu\n", no_lines);
}
Another way to express it is: "Count the number of \n
, and if the last read character is NOT \n
, then add one."