2017-09-18 42 views
0

有人可以找到我的错误是在这个代码中吗?我必须从命令行读取该课程注册文件,该文件具有不同学生ID的类名和优先级(ClassName StudentID Priority,每行),并输出三个文件(每个类),其中包含先入先出的文件。我不允许看到优先级队列类,但int是该学生的优先级。另外,我需要三个输出文件的流?分割错误(核心转储) - 从命令行读取文件

// Course Enrollment 
#include <string> 
#include <fstream> 
#include "p2priorityqueue.h" 
#include <iostream> 
using namespace std; 

int main(int argc, char* argv[]){ 

// Declare filename string, check if there are actually arguments, pass argv[1] (the file used 
// during compilation) to filename variable; 
string filename; 
if(argc > 0){ 
filename = argv[1]; 
} 

// Declare the three variables we will use for passing data to our priority queues. 
string classN; 
string userID; 
int userYear; 

// Declare three Priority Queues for each CS class, each with a string for the student ID and int for 
// priority. 
PriorityQueue<string, int> pq352; 
PriorityQueue<string, int> pq365; 
PriorityQueue<string, int> pq332; 

// Initialize the three Priority Queues as instructed 
initialize(pq352); 
initialize(pq365); 
initialize(pq332); 
// Create input file stream called "input", and three output streams for each class 
ifstream input; 
ofstream output1; 
ofstream output2; 
ofstream output3; 

// Open the file passed at compilation 
input.open(filename.c_str()); 


// While loop that runs until file input stream is empty. The first word is 
passed to classN, 
// the second is passed to userID, and the third to userYear. We then check 
what PQ that line should belong 
// to by comparing classN to CS352, CS365, CS332. 
while(!input.eof()){ 
    input >> classN >> userID >> userYear; 
    if(classN == "CS352"){ 
     push(pq352, userID, userYear); 
    } 
    if(classN == "CS365"){ 
     push(pq365, userID, userYear); 
    } 
    if(classN == "CS332"){ 
     push(pq332, userID, userYear); 
    } 
} 
// close the file input stream. 
input.close(); 



output1.open("CS352"); 
while(!isEmpty(pq352)){ 
    output1 << pop(pq352); 
    output1 << endl; 
} 
output1.close(); 

output2.open("CS365"); 
while(!isEmpty(pq365)){ 
    output2 << pop(pq365); 
    output2 << endl; 
} 
output2.close(); 


output3.open("CS332"); 
while(!isEmpty(pq332)){ 
    output3 << pop(pq332); 
    output3 << endl; 
} 
output3.close(); 

destroy(pq352); 
destroy(pq365); 
destroy(pq332); 
} 

回答

0

尝试初始化所有变量以首先消除任何未初始化的异常。

它看起来像你试图位移未初始化的变量。

即:

string classN = ""; 
string userID = ""; 
int userYear = -1; 

这些在这里可以留下这样的:

ifstream input; 
ofstream output1; 
ofstream output2; 
ofstream output3; 

您还需要防范未初始化的文件名:

string filename; 
if(argc > 0){ 
    filename = argv[1]; 
} else { 
    filename = "somefilename.txt" 
} 

否则这个像input.open(filename.c_str());将失败因为文件名未初始化。

+0

我初始化classN为“”,userID为“”,userYear为0,我得到相同的错误。 –

+0

编辑:还有其他未初始化的变量,我错过了 –

+0

我没有访问p2priorityqueue.h。我已经提供了我可以使用的方法/功能,但没有别的。 –