You can check if line is empty or not by simply using string::empty()
. Here I have used std::ws
to extract the leading whitespaces (if any).
Code :
#include <iostream>
#include <istream>
#include <fstream>
#include <string>
int main() {
std::ifstream fin("car.txt");
if (not fin) {
std::cerr << "car.txt not found in working directory!";
return -1;
}
std::string str;
int n = 0;
while (fin >> std::ws and std::getline(fin, str))
if(not str.empty())
++n;
std::cout << n;
}
This will ignore the empty line(s) (the ones having just whitespaces). Moreover, the main problem with your code was that you were using getline
when EOF
was just about to be reached. You needed to check the condition after reading the input.
Here, in my code, first getline
will be evaluated and then fin
(returned by getline
) will be checked; it will tell us if last operation has succeeded or failed. In case EOF
has been reached, it will fail, and consequently, the while
loop will terminate.
Refer this thread for more information : Why is iostream::eof
inside a loop condition (i.e. while (!stream.eof())
) considered wrong? I would like to quote a comment from it : just because we haven't reached the EOF, doesn't mean the next read will succeed.