Where is the mistake?

lifesamd

Honorable
Jan 14, 2013
9
0
10,510
Code:
#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?
 

lifesamd

Honorable
Jan 14, 2013
9
0
10,510



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?
 

PhilFrisbie

Distinguished
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.
 

lifesamd

Honorable
Jan 14, 2013
9
0
10,510



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