Getting error when counting the number of lines of text in a text file in c++

StackOverflow https://stackoverflow.com/questions/23590197

  •  19-07-2023
  •  | 
  •  

Вопрос

I am trying to count the number of lines in a text file but each time i'm running this code i am getting 1987121509 as the number of lines. Can you please tell me how i can modify my code to get the correct number of lines? Thank you.

Here's the code:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
string line;
int numLine;

ifstream dataFile;
dataFile.open("fileforstring.txt"); 

if(!dataFile)
{
    cout<<"Error opening file.";
}

else
{
    cout<<"File opened successfully";
}

while(getline(dataFile,line))
{
    ++numLine; //increment numLine each time a line is found
}

cout<<"\nNo of lines in text file is "<<numLine;

dataFile.close();

return 0;
}
Это было полезно?

Решение

Here's the correct code(I found out after asking the question) Silly mistake of not initializing the variable correctly.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine = 0; //didn't set it to zero.
ifstream dataFile;
dataFile.open("fileforstring.txt");

if(!dataFile)
{
    cout<<"Error opening file.";
}

else
{
    cout<<"File opened successfully";
}

while(getline(dataFile,line))
{
    ++numLine;
}

cout<<"\nNo of lines in text file is "<<numLine;

dataFile.close();

return 0;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top