我似乎在从文件中读入时遇到问题

I seem to be having a issue reading in from a file

本文关键字:遇到 问题 文件      更新时间:2023-10-16

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

为了不提交一些巨大的文件,我只打算提交我的主函数,因为我假设错误在那里,我只是不确定在哪里。

  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 }

不要为您读取的每个条目打开文件。除此之外,打开每个条目的文件意味着您始终从文件的开头开始阅读。

更改此设置:

 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