Sign in with
Sign up | Sign in
Your question

Where is the mistake?

Last response: in Applications
Share
February 3, 2013 11:40:50 AM

  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

a b L Programming
February 4, 2013 9:50:30 PM

First, are you SURE the file does not contain more than two carriage returns?

Second, 'main' is not prototyped properly ;) 
m
0
l
February 5, 2013 2:20:44 PM

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?
m
0
l
Related resources
a b L Programming
February 5, 2013 9:25:15 PM

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.
m
0
l
February 6, 2013 5:32:08 PM

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 
m
0
l
a b L Programming
February 6, 2013 7:06:55 PM

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.
m
0
l
!