Why is this line getting printed? |
There can be two reasons:
1. istream::getline() encountered a line in your file that was more than 254 characters in length. It sets the failbit if it
fails to get the entire line.
2 istream::getline() was unable to extract *any* characters, the file was empty or already at the end (your case), there was nothing more to read. It sets both eofbit and failbit in that case.
std::getline
(the one that writes into strings) does the same thing when called with an empty file or file at end.
Based on you looking at errno, I think you meant to check for the badbit, not the failbit. The conditions that set failbit have no effect on errno in any case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string finalLine;
ifstream inputFile("test.txt");
while(getline(inputFile, finalLine))
{
cout << finalLine << '\n';
}
if (inputFile.bad())
{
cout << "Error while reading file test.txt: " << std::strerror(errno) << '\n';
}
}
|
PS: that memset() looks silly: first, you can initialize arrays to zero, second, you don't need to initialize them anyway if you're using istream::getline().