[英]Trouble with array with a .txt file
// Declareing variables
const int ARRAY_SIZE = 12; // Array size
int numbers[ARRAY_SIZE]; // Array with 12 elements
int highest, lowest, total = 0, count = 0;
double average;
ifstream fs;
/***** Processing Section *****/
fs.open ("numbers.txt");
if (fs.is_open())
{
cout << "Successfully opened numbers.txt\n";
fs.close();
}
else
{
cout << "Error opening file";
}
while (count < ARRAY_SIZE && fs >> numbers[count])
{count++;
highest = numbers[ARRAY_SIZE];
for (count = 1; count < ARRAY_SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers [count];
}
lowest = numbers[ARRAY_SIZE];
for (count = 1; count < ARRAY_SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers [count];
}
for (int count = 0; count < ARRAY_SIZE; count++)
total += numbers[ARRAY_SIZE];
for (int count=0; count < ARRAY_SIZE; count++)
total += numbers[ARRAY_SIZE];
average = total / ARRAY_SIZE;
}
该代码使用一个number.txt文件,其编号为:47 89 65 36 12 25 17 8 62 10 87 62
我的程序不断向我输出错误的结果,例如:
成功打开numbers.txt
最高值为0
最低值是3
这些数字的总和为0
平均值是2.09204e-317
立即发生一个错误:您正在访问超出范围的数组元素:
highest = numbers[ARRAY_SIZE];
数组从0开始索引,因此最高索引是ARRAY_SIZE - 1
。 您会犯lowest
错误。
最简单的解决方案是执行以下操作:
highest = numbers[0];
//...
lowest = numbers[0];
第二个错误是您没有首先将所有数字读入数组。 由于此程序希望您使用数组,因此您更有可能应该读取数组中的所有数字,并且一旦读入,就循环查找最高和最低值。
while (count < ARRAY_SIZE && fs >> numbers[count])
count++;
// after this, loop for computing the highest and lowest
第三个错误是您在确认文件存在后关闭了文件。 您应该保持文件打开状态。
if (fs.is_open())
{
cout << "Successfully opened numbers.txt\n";
// do not call fs.close()!!
}
同样,如果文件不存在,请立即返回,不要尝试处理最高和最低值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.