【问题标题】:Visual Studio aborts when filling array from file从文件填充数组时,Visual Studio 中止
【发布时间】:2017-04-26 22:04:58
【问题描述】:

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

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

}

【问题讨论】:

  • 我建议您使用 std::string::size_type 而不是 unsigned 为您的 firstlast。您还需要检查 std::string::npos 的返回值。
  • 你应该阅读std::getline(file, line, '#')
  • Visual Studio 中止?你的意思是你的程序中止了吗?

标签: c++ arrays file


【解决方案1】:

问题 1

使用

while (!file.eof())

通常会导致问题。见Why is iostream::eof inside a loop condition considered wrong?

问题 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++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多