Home > Net >  Why is the text of the file displayed twice
Why is the text of the file displayed twice

Time:09-07

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

#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 . . .

CodePudding user response:

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;
}
  • Related