首页 > 解决方案 > Ifstream 遇到创建随机异常

问题描述

我正在尝试使用 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 处读取访问冲突...。

标签: c++fileioifstream

解决方案


推荐阅读