1

The following function is to return the length of a line that is entered through keyboard. But its saying that (The C Programming language K & R) it will return the length of the line, or zero if end of file is encountered. But when I analyzed with my basic knowledge in C at least it is returning the length of the line till EOF. So when does it returns 0. Or my understanding is wrong. Can anybody clarify me ?

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;
}
harald
  • 5,976
  • 1
  • 24
  • 41
noufal
  • 940
  • 3
  • 15
  • 32

4 Answers4

2

You analyzed the program correctly.

But when I analyzed with my basic knowledge in C at least it is returning the length of the line till EOF

-> It will return 0 when the line is empty

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
2

When there's nothing, EOF will be there e.g. in case of Empty line, c==EOF and you have entered a condition in your for loop that (c=getchar())!=EOF. Thus i won't change and when it will be returned after execution of return i;, it will return 0

I hope this helps.

Shumail
  • 3,103
  • 4
  • 28
  • 35
  • suppose if I am entering like `qwertyEOF`, it should return the number `6` ? right ? – noufal Jun 24 '13 at 12:45
  • No. it will return 9. Read this for explanation of EOF in detail: http://stackoverflow.com/questions/3061135/can-we-write-an-eof-character-ourselves p.s please Vote UP for answer and accept it. it encourages infact ;) – Shumail Jun 24 '13 at 12:47
  • CTRL + D ? As per my knowledge, EOF by definition "is unequal to any valid character code" and there's no such character. in DOS, it used to be CTRL + Z but not now. – Shumail Jun 24 '13 at 13:01
  • Entering EOF at end of line won't make it read EOF infact, it will treat it as normal characters. – Shumail Jun 24 '13 at 13:03
  • 1
    I did understand your point. BTW I didn't mean entering `E, O, F` from keyboard. – noufal Jun 24 '13 at 14:05
  • Accept answer Please then. – Shumail Jun 24 '13 at 14:28
0

If the line is empty, it will return 0.

for (i=0; i < lim-1 && (c=getchar())!=EOF && c!=’\n’; ++i)

First, You set i=0;. If ((c=getchar())==EOF), the for loop won't run and i won't be incremented. The situation is the same when the first character is a \n (in this case i will be incremented later)

0

one of the conditions in the for loop is (c=getchar())!=EOF. So when the line is empty, ie. c==EOF at the first instance itself, it doesnt enter the loop. Hence i won't get incremented and it returns 0.

scarecrow
  • 6,624
  • 5
  • 20
  • 39