I am reading The C Programming Language (K&R). I am trying to understand how EOF works and I believe that upon encountering Ctrl + D at the beginning of a line, EOF is triggered. However at the end of a line, it requires the user to enter Ctrl + D twice. First to flush the input and the second to trigger EOF.
The following program reads input lines from the console and prints the longest. I don't understand why I have to enter Ctrl + D thrice to trigger EOF.
#include <stdio.h>
#define MAXLINE 1000
int getline(char[]);
void copy(char[], char[]);
int main()
{
int len, max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while( (len = getline(line)) > 0)
if(len > max)
{
max = len;
copy(longest, line);
}
if(max > 0)
printf("%s", longest);
return 0;
}
int getline(char line[])
{
int c, i;
i = 0;
for(i = 0; i < MAXLINE - 1 && (c = getchar())!=EOF && c!='\n'; ++i )
line[i] = c;
if(c == '\n')
{
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void copy(char to[], char from[])
{
int i = 0;
while( (to[i] = from[i]) != '\0')
++i;
}