Where is the mistake?


#include<stdio.h>
void main()
{
   long n;
   char a;

   n=0;

   while((a = getchar()) != EOF) {
       if(a == '\n')
         ++n;
   }
   printf("the number of lines is %ld", n);
}


I use this source code for counting the no. of lines in an article that will be typed in. But the problem is that when i use only two '\n', the result still comes out to be 3!!! I dont understand the mistake.. What am i doing wrong?
5 answers Last reply
More about where mistake
  1. First, are you SURE the file does not contain more than two carriage returns?

    Second, 'main' is not prototyped properly ;)
  2. PhilFrisbie said:
    First, are you SURE the file does not contain more than two carriage returns?

    Second, 'main' is not prototyped properly ;)



    Am new to C programming.. Infact am just learning.. on my own that too.. And I got stuck with this program.. I dont really know the terms that you used there.. :P Sorry.. What should I do to correct the error?
  3. Make sure, absolutely sure, your test file only contains two carriage returns, because I do not see a reason the code should not work properly.

    Also, look for a better source of C reference code. It is better to not learn bad habits like using void main() when the C standard prototypes main like this:

    int main();

    or

    int main(int argc, char **argv);

    In other words, main() must ALWAYS return a value.
  4. PhilFrisbie said:
    Make sure, absolutely sure, your test file only contains two carriage returns, because I do not see a reason the code should not work properly.

    Also, look for a better source of C reference code. It is better to not learn bad habits like using void main() when the C standard prototypes main like this:

    int main();

    or

    int main(int argc, char **argv);

    In other words, main() must ALWAYS return a value.



    thanks brother! i found out the mistake i had been making! a dumb mistake really... thanks anyways.. and about a good reference, what do you suggest should I use? Suggest me a book to learn C from so that I do not develop bad habits.. This is gonna be my career base as I am in for the graduation course in Information Technology.. and void main() is what I have been taught in college.. :P
  5. How about sharing the error so anyone who sees this later does not make the same mistake ;)

    I do not know of a current good C reference; it has been 20 years since I taught myself C.
Ask a new question

Read More

Programming Apps