1

I have made a Class called FileReader. This is in my read function of this class. It opens a file and reads it. Of course it puts the content of the file in a variable called "content" of my class. It's at the last line.

std::string file_content;
std::string temp;
std::ifstream file;

file.open(filepath,std::ios_base::in);

while(!file.eof()){

    temp.clear();
    getline(file, temp);

    file_content += temp;
    file_content += '\n';
}

file_content = file_content.substr(0, file_content.length()-1); //Removes the last new line

file.close();

content = file_content;

The file I am opening has the following content :

"Hello\nWhat's up\nCool".

Of course I didn't write exactly \n in my textfile. But as you can see there is no new line at the end.

My problem is, "content" has, whenever I print it to the screen, a new line at the end. But I removed the last new line... What's wrong?

2 Answers2

5

Classic error, using eof before you read instead of after. This is correct

while (getline(file, temp))
{
    file_content += temp;
    file_content += '\n';
}

or if you must use eof, remember to use it after getline not before.

for (;;)
{
    getline(file, temp);
    if (file.eof()) // eof after getline
        break;
    file_content += temp;
    file_content += '\n';
}

It's incredible how many people think that eof can predict whether the next read will have an eof problem. But it doesn't, it tells you that the last read had an eof problem. It's been like this throughout the entire history of C and C++ but it's obviously counter-intuitive because many, many people make this mistake.

john
  • 71,156
  • 4
  • 49
  • 68
4

eof doesn't get set until you attempt to read past the end of the file. Your loop is iterating four times for three lines; the last iteration reads no data, though.

The more correct way to do this is to change your while loop to while (std::getline(file, temp)); this will terminate the loop when it reaches the end of the file, after the third read.

Collin Dauphinee
  • 12,840
  • 1
  • 36
  • 59