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大小,您不应该使用静态数组:)
基于发布的代码的一些注释:
- 你不需要追踪所有的元素
- 你也不在乎文件本身有多长
如何用仅向前读取来完成您似乎想要的操作的示例:
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)
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量