我好像从文件中读到了一个问题

时间:2014-02-27 04:00:40

标签: c++ loops infinite

感谢您提前查看此内容。 我可以让我的代码正确编译和诸如此类的东西,但是在运行时我陷入无限的看似循环中,我每次都必须手动退出。我是从文件中读取数据的新手,我认为这可能是我的错误,但是看看我的代码会有任何帮助。

为了不提交一些巨型文件,我只提交我的主要功能,因为我认为错误在那里,我只是不确定在哪里。

  4 #include "class.h"
  5 #include <fstream>
  6 using namespace std;
  7 
  8 
  9 int main()
 10 {
 11     ifstream external; //declaring input stream for my external file
 12     //external.open("external.txt"); //telling the compiler what the source of my external file is called
 13     //external.close();
 14 
 15     char time[4], course[4], section[3]; //places to store read in values
 16     char dept_name[20];
 17 
 18     table hash_table; //instance of my class
 19 
 20     while(!external.eof()) //while it is not the end of the file
 21     {
 22         external.open("external.txt"); //opens file from location
 23 
 24         external.getline(dept_name, 20); //grabs the info to be input
 25         external.getline(time, 4);
 26         external.getline(course, 4);
 27         external.getline(section, 3);
 28 
 29         external.close(); //closes file until new one must begin
 30 
 31         cin.ignore(5, '\n'); //ignores five characters until next course
 32         hash_table.insert(dept_name, course, section, time);  //inserts to table
 33     }
 34     hash_table.display_all();
 35 }

1 个答案:

答案 0 :(得分:3)

不要为您阅读的每个条目打开文件。除此之外,打开每个条目的文件意味着你总是开始在文件的开头阅读。

改变这个:

 20     while(!external.eof()) //while it is not the end of the file
 21     {
 22         external.open("external.txt"); //opens file from location
 23 
 24         external.getline(dept_name, 20); //grabs the info to be input
 25         external.getline(time, 4);
 26         external.getline(course, 4);
 27         external.getline(section, 3);
 28 
 29         external.close(); //closes file until new one must begin
 30 
 31         cin.ignore(5, '\n'); //ignores five characters until next course
 32         hash_table.insert(dept_name, course, section, time);  //inserts to table
 33     }

到此:

 20     external.open("external.txt"); //opens file from location
 21     while(!external.eof()) //while it is not the end of the file
 22     {
 23         
 24         external.getline(dept_name, 20); //grabs the info to be input
 25         external.getline(time, 4);
 26         external.getline(course, 4);
 27         external.getline(section, 3);
 28 
 29         
 30         cin.ignore(5, '\n'); //ignores five characters until next course
 31         hash_table.insert(dept_name, course, section, time);  //inserts to table
 32     }
 33     external.close(); //closes file