简体   繁体   English

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

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

I have been using this code to read integers from a file but it looks like it is crashing when being used with too many elements. 我一直在使用此代码从文件中读取整数,但是当与太多元素一起使用时,它似乎崩溃了。 The file shows in the first line how many numbers to put in the array and then the next lines have the numbers. 该文件在第一行中显示要在数组中放入多少个数字,然后在下一行中显示该数字。 Testing with 1000000 elements (that is my final goal) seems to crash the program. 用1000000个元素进行测试(这是我的最终目标)似乎使程序崩溃。

Example input file: 输入文件示例:

8
5
6
1
4
9
3
1
2

The code: 编码:

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];  
    }  
}  

What might be the problem and what else reading methods do you suggest using? 可能是什么问题,您建议使用其他阅读方法?

Just use a vector: 只需使用一个向量:

#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...

Reference here: http://www.cplusplus.com/reference/vector/vector/ 此处参考: http : //www.cplusplus.com/reference/vector/vector/

You shouldn't use static arrays for noconst-sizes :) 您不应该将静态数组用于noconst-sizes :)

A few notes based on the code posted: 根据发布的代码的一些注意事项:

  • you don't need to keep track of all the elements 您不需要跟踪所有元素
  • you also don't care how long the file is per se 您也不关心文件本身有多长时间

An example of how to do what you appear to want with a forward only read: 有关如何使用“仅转发”来执行所需操作的示例,请阅读:

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