有人可以在此代码中找到我的错误吗?我必须从命令行中读取这个课程注册文件,该文件具有不同学生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 :(得分: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());
这样会失败,因为文件名未初始化。