[英]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.