2017-01-02 161 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(); 
} 
相關問題