你好,亲爱的有帮助的人
我使用seekg()
类的ifstream
函数遇到了问题。我的目标是从已知布局的文本文件中读出一个整数。请将以下示例文件命名为Ph_Sn.cfg。
some random text bla bla
48 molecules of all types
much more text
and numbers etc etc
在实际程序中,我打开文件并执行多个任务,这些任务需要我在读取位置跳转一下。我已经跟踪了我的问题并创建了一个最小的工作示例,即下面的代码
简而言之:通过调用seekg()
函数移动流游标会以某种方式破坏流对象并生成下一个>> operator设置了一个failbit。
#include <iostream>
#include<fstream>
using std::ifstream;
using std::cin;
using std::cout;
using std::endl;
using std::ios;
int skipline(ifstream&);
int main() {
char *file_name = "Ph_Sn.cfg";
ifstream file;
int input;
file.open(file_name);
skipline(file); //skipping a certain amount of lines (here: 1) since I know the file layout
const ifstream::streampos correctPosition = file.tellg(); //stream position before the integer I want to read
file>>input;
cout<<"Integer of interest: "<<input<<endl; //check if integer was read correctly
file.seekg(ios::beg); //revert to start of the file, just for demonstration in this example
skipline(file);
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking flags just for demonstration
file.seekg(correctPosition); //if this line is commented out, the second reading succeeds
cout<<"after seekg comparison tellg==correctPosition "<<(file.tellg()==correctPosition)<<endl; //after calling seekg the position is still correct
cout<<"after seekg: good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //checking again, still no errors
file>>input; //attempt to read out the integer again
cout<<"Integer of interest: "<<input<<endl;
cout<<"good flag, failbit, badbit, eof = "<<file.good()<<" "<<file.fail()<<" "<<file.bad()<<" "<<file.eof()<<endl; //the >> operator set the fail flag
cin>>input; //I don't want the console to close to see the output
return 0;
}
int skipline(ifstream &file)
{
int code;
if(!file)
return(0);
else
{
do
{
code=file.get();
}
while (code!=10);
}
return(1);//no error
}
编译代码并在我的Ph_Sn.cfg所在的目录中运行.exe文件,在控制台上给出了以下输出:
Integer of interest: 48
good flag, failbit, badbit, eof = 1 0 0 0
after seekg comparison tellg==correctPosition 1
after seekg: good flag, failbit, badbit, eof = 1 0 0 0
good flag, failbit, badbit, eof = 0 1 0 0
Integer of interest: 0
正如代码注释中所提到的,只需注释掉file.seekg(correctPosition);
操作,就会在第二次读取时给出正确的整数。
我试图找到类似问题的答案,但在大多数情况下,设置了eof标志,并通过调用file.clear()
解决了问题。遗憾的是,这似乎对我的情况没有帮助。我也找到this post,但我认为我的问题不同(因为我可怕的错误?):
seekg()
之后设置,而是在&gt;&gt;之后设置操作我想知道问题不在于代码,而在于我的eclipse设置。如果代码有效,我想有一个构造,如果是独立编译的话,如果是这样,那么(在我看来)奇怪的行为可能是什么样的设置。 我正在运行32位Windows操作系统,带有cdt插件的eclipse-Luna和MinGW GCC工具链。
我感谢任何帮助或提示。这个问题让我现在待了整整一个星期。