Reputation: 929
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;
}
Upvotes: 1
Views: 161
Reputation: 929
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;
}
Upvotes: 1