Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1066
  • Last Modified:

count the number of lines.

hi everyone,

i was just wondering if you could give me an idea on how to count the lines say for example a text file that contains a number of lines?

i have been running this in my code but i dont know if i am in the right track.

ifstream file("file.txt");
int count = 0;
char line[80];

if(count > 0)
cout << "the number of lines is: " << count << endl;
return 0;

now running this code always gives me a total of 1. can you tell me where the problem is? i'm a begginer of c++.
  • 2
1 Solution
Your problem is the conditional statement of your while() loop.

original: while(file.eof())
should be: while(!file.eof())

file.eof() will return 'true' if the file handle is at the end of the file; 'false' when it is not at the end.  So knowing this, you want the loop to continue if the file handle is not at the end of the associated file... and to do this you need to test for !file.eof().  

(remember, it will return 'false' when we want it to continue through the while() loop... but while() loops require that the condition be met if it is to continue, so to do this we add the 'not' to make it fit our implementation.)
My friend did something rather funny when he got assigned the same problem. It was a UNIX console so he called the wc command and passed the output to a file, read the first number then removed the file. Kinda like wc a.txt > wc.txt.
We had a big laugh when the teacher decided not to call that *cheating* =)
TumbiAuthor Commented:
sorry about that i forgot to put the !file.oef() in the question, but i did that in my code just for got to place it in my question.
Actually... I'm just noticing this... you need to add another closing curly bracket after "++count;" as well.

Because, you are returning a value for the function before you have a chance to make another itteration in the while() loop.


Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now