我正在尝试使用ifstream从.txt文件中读取一些数据,以便将其传递到我创建的类的值中。此函数在类的内部,因此不会在函数的顶部声明整数。 ifstream适用于我读入的前几个值,但是它在其中一行中随机抛出异常(我不知道为什么)。每隔一段时间(好像是50分之一),流将正常工作。
我尝试更改输入文件的格式。如果我在文件的顶部放置一行(然后读入测试编号),则可以解决我的问题。但是,对于该程序,我无法更改输入文件的格式。
int parameters::readParameters() {
ifstream in_stream;
string paramFile = "data/Parameter.txt";
string label;
string option;
// read in file
in_stream.open(paramFile);
// file isn't opened
if (in_stream.fail()) {
cerr << "\nFailed opening Parameter.txt\n";
return 1;
}
// read non data line
in_stream >> label;
// figure out objective
int optionPicker = 0;
int numOptions = 4;
for (int i = 1; i <= numOptions; i++) {
in_stream >> label >> option;
if (option == "Y") optionPicker = i;
}
if (optionPicker == 1) obj = minAvgBid;
else if (optionPicker == 2) obj = maxFirstBid;
else if (optionPicker == 3) obj = maxFithOrBettterBid;
else if (optionPicker == 4) obj = maxNumFivePerTeam;
else obj = none;
// read non data line
in_stream >> label;
/*
The Error occurs directly after this comment
*/
// read upper bounds
in_stream >> label >> maxNumProj;
in_stream >> label >> worstRanking;
// read non data line
in_stream >> label;
// read lower bounds
in_stream >> label >> minNumFiveTeam;
in_stream >> label >> minNumFirstBid;
in_stream >> label >> minNumFifthBid;
// read non data line
in_stream >> label;
// read english options
int english;
in_stream >> label >> english;
if (english == 1) engOpt = option1;
else if (english == 2) engOpt = option2;
else if (english == 3) engOpt = option3;
else if (english == 4) engOpt = option4;
// read native english
string nativeEng;
in_stream >> label >> nativeEng;
if (nativeEng == "Y") native = choice1;
else native = choice2;
// read non data line
in_stream >> label;
// read solution number
in_stream >> label >> solNum;
//if (checkParameters() == 1) return 1;
in_stream.close();
cout << "Parameters Read!" << endl;
return 0;
}
-----------------------------输入文件---------------- ------------
Choose_ONE_objective:
Min_avg_bid Y
Max_first_bid N
Max_fifth_bid N
Max_five_teams N
Choose_Upper_Bounds:
UB_num_proj 60
UB_bid 10
Choose_Lower_Bounds:
LB_5_teams 0 <- the error occurs on this line
LB_first_bid 0
LB_fifth_bid 0
Choose_English_Option:
English_Option 2
Native_English_Lowest Y
Select_Output_Label:
Solution_Number 20
引发异常:访问冲突读取为0x000。...