C++程序崩溃中的文件读取错误

File reading Error in C++ Program crashing

本文关键字:文件 读取 取错误 程序 崩溃 C++      更新时间:2023-10-16

我一直在使用这段代码从文件中读取整数,但当与太多元素一起使用时,它看起来像是崩溃了。该文件在第一行显示要在数组中放入多少数字,然后在下一行显示这些数字。使用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大小,您不应该使用静态数组:)

基于发布的代码的一些注释:

  • 你不需要追踪所有的元素
  • 你也不在乎文件本身有多长

如何用仅向前读取来完成您似乎想要的操作的示例:

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)
}