2017-01-02 142 views
1

我在运行下面的代码时遇到问题。每次我设置了while循环到达.EOF()返回一个std :: bad_alloc的为什么我得到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 funtion失败。这里是读取功能的代码:

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 ::的矢量 和菜单式的std ::的名单

+3

请参阅这篇文章:为什么是的iostream :: EOF算错了一个循环条件中(http://stackoverflow.com/questions/ 5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Rakete1111

+0

谢谢@ Rakete1111 – Akatosh

+1

另外,为读取的每一行调用分配器会减慢程序的运行速度。最好使用非本地'std :: vector'并发出'resize()'调用,而不是每次发出'new/delete'调用。 – PaulMcKenzie

回答

1

我看到的主要问题是:

  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. while声明的条件下拨打电话read

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(); 
} 
相关问题