Reputation: 93
On the C book, (second edition page 29), I read the following content:
/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
int c, i;
for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if(c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
}
My question is: why it is i<lim-1
but not i<lim
in the for condition test? (ps: lim is the maximum length of a line)
Question 2: On C, is EOF
counted as a character?
Upvotes: 1
Views: 94
Reputation: 234715
Space needs to be reserved for the null-terminator \0
that is appended to the string at the end of the loop. (This is how strings are modelled in C).
EOF is a special value that denotes the end of a file. Note how getchar()
returns an int
: this is chiefly so the value of EOF doesn't have to be within the range of a char
.
Upvotes: 2