Reputation: 1
I have a project and I'm supposed to count the lines, words and characters in a file. My program works fine but I'm not supposed to count a blank line in the end of file if there is one.
How can I avoid counting a blank line in the end of a file if there is one? I can assume there is at most one blank line in the end of the file.
Here's the loop where I'm counting the lines:
int count_lines(fstream& infile) {
int counter_lines=0;
string unused;
while ( getline(infile, unused) ) {
counter_lines++;
}
infile.close();
return counter_lines;
}
Upvotes: 0
Views: 695
Reputation: 89
Use a separate counter for blank lines.. and discard the counter if you encounter EOF, else add it to the actual count of lines. This will discard multiple blank lines at the end of the file.
Upvotes: 1
Reputation: 8514
Have a bool
variable to indicate if the line read was blank, call it lastLineWasBlank
(initialise it to false). Then each time around the loop, set it to unused.empty()
.
When your loop finishes, if lastLineWasBlank
is true, subtract one from the count.
You might then want to change unused
to a different variable name.
Upvotes: 3