Reading to end of text file and displaying line count

SO i am trying to write a program that asks the user for input and then opens a file that is of that input name... My program attempts to read the file and then display the line count but it keeps getting stuck in an infinite loop when using ifstream::elf()

here is the code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main(int argc, const char * argv[])
{
    string fileName;
 
    cout << "Enter file name: ";
    cin >> fileName;
    

    int lineCount=0;
    ifstream inputFile(fileName.c_str());
    
    while(!inputFile.eof())
    {
        lineCount++;
     
        
        
    }
    inputFile.close();
    cout << "Line count: " << lineCount;
    
}


Thanks!
1
2
3
4
    while(!inputFile.eof())
    {
        lineCount++;
    }
So you want to know how much time it takes the water to boil... but forgot to start the fire.
Still, you shouldn't use eof()
1
2
while( getline(input, line) )
   count++;
Thanks for the reply:) anyway why wouldnt i want to use eof? and I didn't know the getline function could be used as a checker for the end of the file, how does that work? Also, what is the line param? is it a string var?

Last edited on
eof activates when you try to read but you are at the end of the file.
So you will count one too many (depending if your file ends with a line break)

If an stream is valid then it evaluates as true

Yes, line is a std::string
Last edited on
Topic archived. No new replies allowed.