2017-04-24 57 views
0

我需要在文件中取未知數量的整數並將它們存儲到一個矢量中,從最大到最小排序並查找最小的調和平均值和最大的數量。然後我需要將文件中的均值和所有數字輸出到一個新文件中。我創建了一個完美適用於小於10的整數的代碼,但它將數字作爲字符串輸入到矢量中,我需要重寫代碼以將整個文件的每一行輸入爲整數,但出現錯誤。它不會輸出任何內容到「AverageFile」,程序在加載後會崩潰。它給出了錯誤從.txt文件中取出數字並將它們放入C++中的矢量中

「終止叫做拋出的一個實例後‘的std :: bad_alloc的’什麼()的std :: bad_alloc的」

我的代碼如下,我認爲這個問題是輸入或輸出矢量。

#include <iostream> 
#include <fstream> 
#include <string> 
#include<stdlib.h> 
#include<vector> 
using namespace std; 

int main() 
{ 
    int line; 
    vector<int> score; 
    int i=0; 
    //double sum=0; 
    //double avg; 
    int temp=0; 

    string x; 
    cin>>x; 
    ifstream feederfile(x.c_str()); 

    if(feederfile.is_open()) 
    { 
     while(feederfile.good()) 
     { 
      score.push_back(line); 
      i++; 
     } 

     feederfile.close(); 
    } 
    else cout<<"Unable to open Source file"; 

    //Sorting from greatest to least: 
    for(int i=0;i<score.size()-1;i++) 
    { 
     for(int k=i;k<score.size();k++) 
     { 
     if(score[i]<score[k]) 
     { 
      temp=score[i]; 
      score[i]=score[k]; 
      score[k]=temp; 
     } 
     } 
    } 

    int a=score[score.size()-1]; 
    int b=score[0]; 
    double abh=2/(1/double (a)+1/double (b)); 
    ofstream myfile ("AverageFile.txt"); 

    if(myfile.is_open()) 
    { 
     myfile<<"The Harmonic Mean is: "<<abh<<endl; 
     myfile<<"Sorted Numbers: "; 
     for(int i=0;i<score.size();i++) 
     { 
      if(i<score.size()-1) 
      { 
       myfile<<score[i]<<", "; 
      } 
      else{myfile<<score[i];} 
     } 
    myfile.close(); 
    } 
    else cout<<"Unable to open Export file"; 
    return 0; 
} 
+1

'feederfile'應該是'ifstream'還是'ofstream'? – Beta

+0

對不起,忘了刪除'ofstream'它應該是ifstream – Uncblueguy

回答

4

你忘了從檔案中讀取。在

while(feederfile.good()){ 
    score.push_back(line); 
    i++; 
} 

你永遠不會從文件中讀取,所以你有一個無限循環的文件將永遠是good(),最終你耗盡內存試圖對象添加到載體。使用feederfile.good()is not what you want to use for your condition。相反,您希望使讀操作成爲循環條件。所以如果我們這樣做,那麼我們有

while(feederfile >> line){ 
    score.push_back(line); 
    i++; 
} 

這將讀取,直到遇到錯誤或文件的結尾。

+0

謝謝!它終於有效。 – Uncblueguy

相關問題