简体   繁体   中英

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

This code uses a number.txt file with the numbers: 47 89 65 36 12 25 17 8 62 10 87 62

My program keeps outputting me the wrong results like:

Successfully opened numbers.txt

The highest value is 0

The lowest value is 3

The sum of the numbers is 0

The average of the numbers is 2.09204e-317

One error right away: you are accessing an array element that's out of bounds:

    highest = numbers[ARRAY_SIZE];

Arrays are indexed starting from 0, so the highest index is ARRAY_SIZE - 1 . You make the same mistake with lowest .

The easiest solution is to do this:

highest = numbers[0];
//...
lowest = numbers[0];

The second error is that you haven't read all your numbers into the array first. Since this program wants you to use arrays, more than likely you're supposed to read all the numbers in the array, and once read in, you loop to figure out the highest and lowest.

while (count < ARRAY_SIZE && fs >> numbers[count]) 
   count++;
// after this, loop for computing the highest and lowest 

The third mistake is that you closed the file after confirming that it exists. You should keep the file open.

if (fs.is_open())
{
   cout << "Successfully opened numbers.txt\n";
   // do not call fs.close()!!
}

Similarly, if the file does not exist, return right away and don't attempt to process the highest and lowest values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM