Search code examples
c++ifstream

read last line in c++


for some reason, my program doesn't print the last line of a textfile if the last line contains less characters than the buffer

#include <iostream>
#include <iomanip>
#include <fstream>

int main()
{
    std::ifstream read("test.txt");
    char buffer[12];

    while(!read.eof())
    {
        read.getline(buffer,11);
        if(!read.eof())
            std::cout<<buffer<<'\n';
        read.clear();

    }
    read.close();

    return 0;
}

Solution

  • You are printing the line out under condition that if(!read.eof()), but that condition will evaluate to false after the last line was read with getline().