Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the text of the file displayed twice

I have been working on a project which needs to read the text from a .txt file. But I get the text displayed in the console twice.

Here is the CreateFiles.cpp

#include "CreateFiles.h"
void createF()
{
    std::fstream fs{ "C:\\Users\\bahge\\source\\repos\\Education\\Education\\myfile.txt" };

    std::string s;

    while (fs)
    {
        std::getline(fs, s);
        
        std::cout << s << std::endl;
    }
}

And the CreateFiles.h

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#pragma once
#ifndef CREATE_FILES
#define CREATE_FILES
#include <iostream>
#include <fstream>
#include <string>
void createF();
#endif // !CREATE_FILES

Here is the file’s content

StackOverflow

And the output from the console

StackOverflow
StackOverflow

C:\Users\bahge\source\repos\Education\x64\Debug\Education.exe (process 39072) exited with code 0.
Press any key to close this window . . .

>Solution :

You are encountering a variation of Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.

You are ignoring the stream’s state after getline() returns. Your file has only 1 line in it, so s is not valid (and in your case, is unchanged) after the 2nd read fails, but you are not handling that condition correctly, so you are printing s when you should not be.

You need to change your loop from this:

while (fs)
{
    std::getline(fs, s);
    std::cout << s << std::endl;
}

To this instead:

while (std::getline(fs, s))
{
    std::cout << s << std::endl;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading