Line Counting Program in C -


i learning c language book called "the c programming language" brian kernighan & dennis ritchie , have been stuck @ basic lesson of line counting program. program runs not give output of how many lines inputed.

have given program code below, please on same.

#include <stdio.h>  void main() {     int c, nl;     nl = 0;     while ((c = getchar()) != eof )         if (c == '\n')             ++nl;     printf("%d \n", nl);      return 0; } 

the code should read input , output how many lines of text given. how should changed make work?

your program works fine. however, prefix main int type keep compiler quiet. should this:

int main(void)

when call it, did this:

$$$ ->./test6 < test4.c 19 $$$ ->wc test4.c       19      48     379 test4.c $$$ -> 

the getchar function same thing getc(stdin), when run program, takes it's input stdin (keyboard) or file redirected stdin.

edit: pointed out, if last line doesn't have \n terminator, line not counted. rewrote code account this:

#include <stdio.h>  int main(void) {     int c;  /* character */     int cp; /* previous character */     int n;  /* number of lines */      n = 0;     c = 0;     while (1)     {         cp = c;         c = getchar();         if (c == '\n')         {             n++;             continue;         }         if (c == eof && cp == '\n') break;         if (c == eof)         {             n++;             break;         }     }     printf("%d \n", n);      return 0; } 

as can see in code, used fall-though logic either continue loop or break out of it. tested code using clang on freebsd , works properly.

the logic of program follows:

  1. save current character previous character.
  2. get next character , make current character.
  3. check current character see if it's newline character.
  4. if is, increment line counter , restart loop.
  5. check current character see if it's eof , previous character see if it's newline character.
  6. if is, break out of loop.
  7. check current character see if it's eof.
  8. if is, increment line counter , break out of loop.

that how deal final line not being terminated newline character , still have counted line. note considered special case , needs explicitly coded for. if continue software development profession, encounter special case situations lot , need code handling each 1 encounter.

hope helps.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -