问题描述:我使用fstream读取文件,当我使用istream :: operator>>提取数据时。我发现死循环,getline()似乎不起作用。而且,代码无法找到所有关键字。我找不到问题的原因。 inputfile中:
1001011 2001311 7.548735960e-018 9.524005670e-001
@contact 0 2
glob_id nbr_id force b
1001009 2001309 1.936503748e-013 5.980546471e + 000
1001009 2001309 1.936503748e-013 5.980546471e + 000
1001011 2001311 7.548735960e-018 9.524005670e-001
代码:
#include <iostream>
#include <cstdlib>
#include<cstdio>
#include<fstream>
#include <map>
#include <string>
using namespace std;
int main()
{
fstream file;
char fileName[128];
char keyWord[128]={"@contact"};
char tempWord[256];
//sprintf()
int step=0,substep=0;
unsigned long globelId=0;
unsigned long nbr_id=0;
double bForce;
double Force;
bool bNextLineEmty=false;
file.open("demo.text",fstream::in);
if(!file.is_open())
{
cout<<"Error Opeing File!" <<endl;
}
while (!file.eof())
{
file.getline(tempWord,256);
char dumpChar[256];
int pos=0;
if(strncmp(keyWord,tempWord,7)==0)
{
// judge next line is blank or not
while(!bNextLineEmty)
{
file.getline(dumpChar,256);
pos=file.tellg();
file.getline(dumpChar,256);
// if next line is blank,then bNextLineEmty is Ture,
if (strcmp(dumpChar,"")==0)
{
bNextLineEmty=true;
}
file.seekg(pos,ios::beg);
pos=file.tellg();
//read data
file>>globelId>>nbr_id>>Force>>bForce;
}
}
}
return 0;
}