为什么我收到std :: bad_alloc错误

时间:2017-01-02 02:52:35

标签: 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 个答案:

答案 0 :(得分:1)

我看到的主要问题是:

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

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

  3. 我建议:

    1. 更改read版本以返回对ifstream的引用。它应该返回它作为输入所需的ifstream。这样就可以在循环条件下使用对read的调用。

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

    3. read声明为条件致电while

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