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

x
  • 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];

while(file.eof())
{
file.getline(line,80);
++count;
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++.
0
Tumbi
Asked:
Tumbi
  • 2
1 Solution
 
SIC_MichaelCommented:
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.)
0
 
n_fortynineCommented:
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* =)
0
 
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.
0
 
SIC_MichaelCommented:
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.

0

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