Reputation: 1018
I have created this function to return the number of lines in a text file:
int numberOfLinesInFile(string dataFile){
ifstream inputFile;
inputFile.open("data.txt");
int numberOfLines, data;
while(!inputFile.eof()){
inputFile >> data;
numberOfLines++;
}
cout << "Number of lines: " << numberOfLines << endl;
inputFile.close();
return numberOfLines;
}
An interesting thing that I noticed is that the function counts the number of the non-blank lines (and an additional blank line at the end) correctly, but the additional blank lines are not being counted. For example, if this is my file:
234
453
657
then the function returns 4
, since there are four lines in the text file. However, if my file contains more than one blank line at the end:
234
453
657
the function returns 4
again.
Why is this happening? Does this have to do with the eof
instruction?
EDIT:
Okay, thank you @MikeCAT for making me understand where the problem was. Based on @MikeCAT's answer, I changed the while
loop as:
while(!inputFile.eof()){
if(inputFile >> data)
numberOfLines++;
else{
cout << "Error while reading line " << numberOfLines + 1 << "!" << endl;
}
}
I was incrementing numberOfLines
without making sure that the line was actually read.
Upvotes: 1
Views: 165
Reputation: 75062
Firstly, you are doing numberOfLines++;
after inputFile >> data;
without checking if the reading is successful. This is bad and lead to an extra counting.
Secondly, inputFile >> data;
reads integer and skip whitespace characters before integers.
To avoid these problems, you should use std::getline()
to count lines.
Also don't forget to initialize numberOfLines
.
int numberOfLinesInFile(string dataFile){
ifstream inputFile;
inputFile.open("data.txt");
int numberOfLines = 0;
std::string data;
while(std::getline(inputFile, data)){
numberOfLines++;
}
cout << "Number of lines: " << numberOfLines << endl;
inputFile.close();
return numberOfLines;
}
Upvotes: 2