提问人:Coder 提问时间:5/30/2015 最后编辑:AnthonCoder 更新时间:5/30/2015 访问量:104
从文件中读取数据时的无限循环
Infinity loop while reading data from file
问:
我正在尝试从文件中读取数据。有三行。我所做的是下面。问题是(文件存在)在读取文件时它是无限循环。我观察到程序在到达文件末尾之前不会逐行移动。我的代码中有什么错误?
法典:
if (desktops == NULL) {
printf("\n No such file.\n");
} else{
printf("\nFile exists. Reading\n");
while(!feof(desktops)){
if(numberOfObjects== 0)
{
fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n",&height,&length,&width,&processorClock,&idNumberSerial,&processorTypeChars,&nameInNetworkChars,&ID);
nameInNetwork = string(nameInNetworkChars);
processorType = string(processorTypeChars);
// nameInNetwork = "test";
glowaListyObjektow = new Desktop(height,length,width,processorClock,idNumberSerial,processorType,nameInNetwork,ID);
iterator = glowaListyObjektow;
iterator->previousObject = NULL;
iloscObiektow++;
nameInNetwork.clear();
processorType.clear();
}
else if(numberOfObjects> 0)
{
fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n",&height,&length,&width,&processorClock,&idNumberSerial,&processorTypeChars,&nameInNetworkChars,&ID);
nameInNetwork = string(nameInNetworkChars);
processorType = string(processorTypeChars);
// nameInNetwork = "test";
iterator->nextObject = new Desktop(height,length,width,processorClock,idNumberSerial,processorType,nameInNetwork,ID);
iterator->nextObject->previousObject = iterator;
iterator = iterator->nextObject;
iloscObiektow++;
nameInNetwork.clear();
processorType.clear();
// nameInNetworkChars = NULL;
}
cout<<"reading line"<<endl;
// Here line above is printed infinitely.
}
fclose(desktops);
}
答:
0赞
R Sahu
5/30/2015
#1
我看到的问题。
- 您使用的格式是错误的,而不是 .
%fl
%lf
- 您没有检查是否成功读取数据。
fscanf
改变
fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n", &height, &length, &width, &processorClock, &idNumberSerial, &processorTypeChars, &nameInNetworkChars, &ID);
自
int n = fscanf(desktops,"%lf %lf %lf %lf %d %s %s %d\n", &height, &length, &width, &processorClock, &idNumberSerial, &processorTypeChars, &nameInNetworkChars, &ID);
if ( n != 8 )
{
// Deal with error condition
}
评论