C++文件读取时有一个bug,就是使用eof()判断文件结尾并不准确,最后一行会重复读取一次,可采用以下方法避免重复读取:
while (!inFile.eof()) { inFile >> …… >>; inFile.get(); // 读取最后的回车符 if(inFile.peek() == '/n') break; }
C语言多读一行,解决方案如下:逐行读取,判断每一行是否获取成功,获取成功则读取,否则中断
FILE *fp = fopen(fileName.c_str(), "r"); if (fp) { while (!feof(fp)) { char line[512]; if (!fgets(line, 511, fp)) { break; } sscanf(line, "%lf%lf%lf", &pot.x, &pot.y, &pot.z); tempPt.push_back(pot); if (pot.x > maxX) maxX = pot.x; if (pot.x < minX) minX = pot.x; if (pot.y > maxY) maxY = pot.y; if (pot.y < minY) minY = pot.y; if (pot.z > maxZ) maxZ = pot.z; if (pot.z < minZ) minZ = pot.z; } fclose(fp);