簡體   English   中英

C ++程序崩潰時文件讀取錯誤

[英]File reading Error in C++ Program crashing

我一直在使用此代碼從文件中讀取整數,但是當與太多元素一起使用時,它似乎崩潰了。 該文件在第一行中顯示要在數組中放入多少個數字,然后在下一行中顯示該數字。 用1000000個元素進行測試(這是我的最終目標)似乎使程序崩潰。

輸入文件示例:

8
5
6
1
4
9
3
1
2

編碼:

ifstream fin;  
ofstream fout;  

fin.open("share.in", ios::in);  
fin >> days;  
int incomes[days];  
for(int i = 0; i < days; i ++){  
    fin >> incomes[i];  
    athroisma += incomes[i];  
    if(incomes[i] > minDiafora){  
        minDiafora = incomes[i];  
    }  
}  

可能是什么問題,您建議使用其他閱讀方法?

只需使用一個向量:

#include <vector>

//...

ifstream fin;  
ofstream fout;  

fin.open("share.in", ios::in);  
fin >> days;  
vector<int> incomes;  /***DECLARATION***/    
incomes.resize(days); /***TAKE SIZE***/

for(int i = 0; i < days; i ++){  
    fin >> incomes[i];  
    athroisma += incomes[i];  
    if(incomes[i] > minDiafora){  
        minDiafora = incomes[i];  
    }  
}

//do something...

此處參考: http : //www.cplusplus.com/reference/vector/vector/

您不應該將靜態數組用於noconst-sizes :)

根據發布的代碼的一些注意事項:

  • 您不需要跟蹤所有元素
  • 您也不關心文件本身有多長時間

有關如何使用“僅轉發”來執行所需操作的示例,請閱讀:

ifstream fin;  
ofstream fout;  
int days;
int income;
int minDiafora = std::numeric_limits<int>::min();
int athroisma = 0;
fin.open("share.in", ios::in);  
fin >> days; // ignore first
while(fin >> income) // implicitly checks to see if there is anything more to read
{
    athroisma += income;
    minDiafora = std::max(minDiafora, income)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM