我正在尝试将库存系统读入结构数组。当我调用该函数并且它到达第一行时我尝试将数据写入数组,我收到错误:
Lab 09.exe中0x777CA932处的未处理异常:Microsoft C ++异常:内存位置0x00F3DC68处的std :: out_of_range。
这是结构:
struct inventory {
int record;
string toolname;
int quantity;
double cost;
};
数组声明:
inventory unsortedArray[100];
这是函数(假设文件的第一行是83 #Electric Sander#7 57.00):
void fillArray(inventory unsortedArray[]) {
ifstream file;
string line;
string delim = "#";
stringstream ss;
file.open("records.txt");
int i = 0;
while (!file.eof()) {
getline(file, line);
unsigned first = line.find_first_of(delim);
unsigned last = line.find_last_of(delim);
unsortedArray[i].toolname = line.substr(first, (last - first) + 1);
line.erase(first, (last - first) + 1);
ss << line;
ss >> unsortedArray[i].record;
ss >> unsortedArray[i].quantity;
ss >> unsortedArray[i].cost;
i++;
}
file.close();
}
答案 0 :(得分:1)
使用
*ngIf="myFlag"
通常会导致问题。见Why is iostream::eof inside a loop condition considered wrong?
使用正确的类型来捕获while (!file.eof())
和std::string::find_first_of
的返回值。
使用
std::string::find_last_of
或
auto first = line.find_first_of(delim);
auto last = line.find_last_of(delim);
在继续使用之前,请务必检查std::string::size_type first = line.find_first_of(delim);
std::string::size_type last = line.find_last_of(delim);
和std::string::find_first_of
的返回值。
std::string::find_last_of
我的建议
使用
auto first = line.find_first_of(delim);
auto last = line.find_last_of(delim);
if ( first == std::string::npos )
{
// Didn't find it. Figure out what to do.
}
if ( last == std::string::npos )
{
// Didn't find it. Figure out what to do.
}
// Both checks are done. Now you can use first and last.