Sign in with
Sign up | Sign in

Where is the mistake?

Last response: in Applications
Share

  1. #include<stdio.h>
  2. void main()
  3. {
  4. long n;
  5. char a;
  6.  
  7. n=0;
  8.  
  9. while((a = getchar()) != EOF) {
  10. if(a == '\n')
  11. ++n;
  12. }
  13. printf("the number of lines is %ld", n);
  14. }


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?

More about : mistake

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?

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.

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 
!