有谁知道为什么我的代码没有从第一行读取文件

Does anyone know why is my code not reading file from first line

本文关键字:一行 文件 读取 为什么 谁知道 我的 代码      更新时间:2023-10-16

我想创建用于延迟字幕的程序,当我运行下面的代码时,没有从第一行读取。它像文件的中间一样分层。

#include "stdafx.h"
#include "iostream"
#include "cstdlib"
#include "fstream"
#include "string"
using namespace std;
int main(int argc, char *argv[]){
     ifstream input; //input
     char input_file[32]; //names of input and output

      cout << "Enter name of input fille: "; ///user gives names of input
      cin >> input_file;
input.open(input_file);
if (!input.good()){
    cout << "File " << input_file << " dosen't exist." << endl;
    return 1;
}

string row;
while (!input.eof()){    
    getline(input, row);
    cout << row << endl;
}
system("pause");
return 0;
}

首先,eof()不应该放在while()中,有关详细信息,请参阅此处。所以改变

while (!input.eof()){    
    getline(input, row);
    cout << row << endl;
}

while (getline(input, row)){       
    cout << row << endl;
}

看看进展如何。从文件中间阅读真的很奇怪。也许您可以进一步将文件的内容分享给我们,以更好地解决问题。

您仍然可以在读取任何内容之前使用 input.seekg(0, input.beg) 手动将位置设置为开头。