Visual Studio从文件中填充数组时中断

Visual Studio aborts when filling array from file

本文关键字:数组 中断 填充 Studio 文件 Visual      更新时间:2023-10-16

我正在尝试将库存系统读取到结构数组中。当我调用该函数并进入第一行时,我尝试将数据写入数组中,我得到了错误:

实验室中的0x77777CA932在09.exe中未经处理的异常:Microsoft C 例外:std :: out_of_range在内存位置0x00f3dc68。

这是结构:

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();
}

问题1

使用

while (!file.eof())

通常会导致问题。查看为什么iostream :: eof内部被认为是错误的?

问题2

使用正确的类型捕获std::string::find_first_ofstd::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);

问题3

在进行使用之前,请务必检查std::string::find_first_ofstd::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.

我的建议

使用

while (getline(file, line)) {
   unsigned first = line.find_first_of(delim);
   unsigned last = line.find_last_of(delim);
   if ( first == std::string::npos )
   {
      break;
   }
   if ( last == std::string::npos )
   {
      break;
   }
   unsortedArray[i].toolname = line.substr(first, (last - first) + 1);
   line.erase(first, (last - first) + 1);
   // Don't use ss << line
   // Construct ss in the loop. You don't need to mess with its
   // old state
   std::istringsteram ss(line);
   ss >> unsortedArray[i].record;
   ss >> unsortedArray[i].quantity;
   ss >> unsortedArray[i].cost;
   i++;
}