为什么文件的文本显示两次

Bah*_*Goz 1 c++ c++20

我一直在从事一个需要从 .txt 文件读取文本的项目。但我在控制台中显示了两次文本。

这是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

CreateFiles.h

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

这是文件的内容

StackOverflow
Run Code Online (Sandbox Code Playgroud)

以及控制台的输出

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 . . .
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 8

您遇到了Why is iostream::eof inside a循环条件(即`while (!stream.eof())`)被认为是错误的变体?。

返回后您将忽略流的状态getline()。您的文件中只有 1 行,因此s在第二次读取失败后无效(在您的情况下,未更改),但您没有正确处理该情况,因此您在s不应该打印的时候进行了打印。

你需要改变你的循环:

while (fs)
{
    std::getline(fs, s);
    std::cout << s << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

为此:

while (std::getline(fs, s))
{
    std::cout << s << std::endl;
}
Run Code Online (Sandbox Code Playgroud)