This exercise asks me to rewrite a getline() function. Originally, it stored up to 1000 chars of the line in an array and returned the length of the line. However, the function would not return the length correctly for arbitrarily long input lines, returning a max of 1000, ignoring anything after the 998th character.
My task was to rewrite getline() to correctly return the length, but still only store the 1000 first characters in the array I pass to it.
Here is the original getline() unmodified:
Code:
/* 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;
}
Here are my modifications. I've tested it with a lower max of 10, but want to make sure I haven't left any holes that anyone more experienced could easily spot.
Code:
/* getline: read a line (1000 char max) into s, return true length */
int getline(char s[], int lim)
{
//length: true length of string regardless of array size limit
//pos: current position in the array limited to 1000 chars
//c: char holder
int length = 0, pos = 0, c = 0;
for (length=0; (c=getchar()) != EOF && c != '\n'; ++length)
{
//only assign to the array if we are under the limit of 998
//need room for '\n' and '\0'
if(length < lim - 1)
s[pos++] = c;
}
if (c == '\n')
{
s[pos] = c;
++pos;
}
s[pos] = '\0';
return length;
}
Thanks in advance for any constructive criticism anyone can provide.
EDIT: I should note that the maximum of 1000 I mentioned is a symbolic constant I pass to getline() in my main().