为什么seekg不能与getline一起工作

Why seekg does not work with getline?

本文关键字:一起 工作 getline seekg 不能 为什么      更新时间:2023-10-16

Seekg似乎不起作用,当我在myFile中达到EOF时。

ifstream myFile("/path/file");
for(int i; i < 10; i++){
    myFile.seekg(0);//reset position in myFile
    while(getline(myFile, line)){
        doSomething
    }
}

那么,现在我在每个循环中打开输入流:

for(int i; i < 10; i++){
    ifstream myFile("/path/file");//reset position in myFile
    while(getline(myFile, line)){
        doSomething
    }
}

但我宁愿寻求位置0。我怎样才能做到呢?

确保在调用myFile.seekg()之前清除错误标志:

myFile.clear();

设置EOF标志后,您将无法提取任何内容。你必须清除这些标志才能再次提取