【问题标题】:Does anyone know why is my code not reading file from first line有谁知道为什么我的代码没有从第一行读取文件
【发布时间】:2014-01-18 12:13:36
【问题描述】:

我想创建延迟字幕的程序,当我运行下面的代码时,不是从第一行读取。 它就像文件中间一样。

#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;
}

【问题讨论】:

标签: c++ ifstream


【解决方案1】:

首先,eof() 不应该放在while() 中,详见here。所以改变

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2016-05-13
      • 2012-09-08
      • 2021-12-24
      相关资源
      最近更新 更多