c++ - 为什么我会收到 std::bad_alloc 错误

标签 c++ fstream eof

我在运行下面的代码时遇到问题。每次我设置 while 循环到达 .eof() 它返回一个 std::bad_alloc

inFile.open(fileName, std::ios::in | std::ios::binary);

        if (inFile.is_open())
        {
            while (!inFile.eof())
            {
                read(inFile, readIn);
                vecMenu.push_back(readIn);
                menu.push_back(readIn);
                //count++;
            }

            std::cout << "File was loaded succesfully..." << std::endl;

            inFile.close();
        }

如果我设置了预定的迭代次数,它运行良好,但当我使用 EOF 函数时失败。这是读取函数的代码:

void read(std::fstream& file, std::string& str)
{
    if (file.is_open())
    {
        unsigned len;
        char *buf = nullptr;

        file.read(reinterpret_cast<char *>(&len), sizeof(unsigned));

        buf = new char[len + 1];

        file.read(buf, len);

        buf[len] = '\0';

        str = buf;

        std::cout << "Test: " << str << std::endl;

        delete[] buf;
    }
    else
    {
        std::cout << "File was not accessible" << std::endl;
    }
}

非常感谢您提供的任何帮助。 注意:我没有提到 vecMenu 是 std::vector 类型 菜单的类型是 std::list

最佳答案

我看到的主要问题是:

  1. 您正在使用 while (!inFile.eof()) 来结束循环。参见 Why is iostream::eof inside a loop condition considered wrong? .

  2. 在使用读入的变量之前,您没有检查对 ifstream::read 的调用是否成功。

我建议:

  1. 更改您的 read 版本以返回对 ifstream 的引用。它应该返回作为输入的 ifstream。这使得在循环条件中调用 read 成为可能。

  2. 在使用前检查对 ifstream::read 的调用是否成功。

  3. 将对 read 的调用放在 while 语句的条件中。

std::ifstream& read(std::fstream& file, std::string& str)
{
   if (file.is_open())
   {
      unsigned len;
      char *buf = nullptr;

      if !(file.read(reinterpret_cast<char *>(&len), sizeof(unsigned)))
      {
         return file;
      }

      buf = new char[len + 1];

      if ( !file.read(buf, len) )
      {
         delete [] buf;
         return file;
      }

      buf[len] = '\0';

      str = buf;

      std::cout << "Test: " << str << std::endl;

      delete[] buf;
   }
   else
   {
      std::cout << "File was not accessible" << std::endl;
   }

   return file;
}

inFile.open(fileName, std::ios::in | std::ios::binary);

if (inFile.is_open())
{
   std::cout << "File was loaded succesfully..." << std::endl;

   while (read(inFile, readIn))
   {
      vecMenu.push_back(readIn);
      menu.push_back(readIn);
      //count++;
   }

   inFile.close();
}

关于c++ - 为什么我会收到 std::bad_alloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420861/

相关文章:

使用 atoi() 函数的 C++ 访问冲突

C++仅覆盖文件段

c - 为什么 fread 循环需要额外的 Ctrl+D 来用 glibc 发出 EOF 信号?

c++ - GMock : Has to be always pure virtual the base class of a mock class?

c++ - 如何在应用程序容器内启动应用程序?

c++ - 以下模板特化代码是非标准的还是 VS-C++ 中的错误?

c++ - 虽然不是新线

c++ - "File could not be opened."C++ fstream

linux - 使用 SVN Diff 时在 Ubuntu Linux 上使用行尾样式的 WinSCP 问题

Android:为什么 BufferedReader 读取 EOF?