Reading an unknown amount of data from file into an array

Hello,

This question pertains to a programming problem that I have stumbled across in my C++ programming class.

The Assignment:
-----------------------------------------------------------------------------------
Number Analysis Program

Write a program that asks the user for a file name. Assume the file contains a series of numbers, each written on a separate line. The program should read the contents of the file into an array and then display the following data:

The lowest number in the array
The highest number in the array
The total of the numbers in the array
The average of the numbers in the array

-----------------------------------------------------------------------------------

My question pertains mainly to reading these numbers from a file, the question doesn't indicate any specific amount of numbers, the list could be any size, I'm at a loss here.

How can I find out how many numbers are in a file,and then use that amount as the iteration count in a for loop to put these numbers in an array?

Any help would be very much appreciated.
There is no direct way. A fixed-size array can always be overflowed.

The C++ answer is to use a std::deque or std::list.

In C, you could dynamically allocate blocks of an array, or a simple linked list.

You could also just count the number of lines in the file, close and reopen it, allocate space for the array, and read it.

You could have a fixed-size array (either statically or dynamically allocated) and simply refuse to read more numbers than the array can handle.

Note also that the tasks presented in this assignment doesn't actually need you to preserve the array itself -- only its min, max, size, and average.

Good luck!
Why so complicated?

You need to read from the file -> "ifstream"
You want each number -> each new line in the file is a "distance", which your compiler should recognize.

So all you have to do is to check if the file is open and put a loop in there. As long as the File "delievers" numbers, you put these into array[Amount]. Of course, "Amount" should be increased in the loop.

-> Filled array, amount of numbers. To check for max/min is trivial.
Last edited on
Because OP does not know beforehand the size of the array to allocate, hence the suggestion
to use a dynamically sizable data structure such as std::deque and std::list.

Ask2i
Why such antagonism?
What happens when Amount >= (sizeof(array) / sizeof(array[0])) ?

Rather than a broken non-answer, I gave the OP five distinct answers, each of which is trivial to implement.
Last edited on
What kind of numbers? floats or ints?


One solution without STL:
make your array "big enough"
1
2
3
4
5
6
7
8
9
#define maxsize 1000000000000 //maybe excessive ;)

int main()
{
    int array[maxsize];
    // ...
    return 0;
}


Another solution without STL:
Read the file twice. Count the number of numbers the first time, allocate an array, read into the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    int *array;
    int tmp, count;

    ifstream fin("inputfile");

    while(fin >> tmp)
        count++;
    
    array = new int[count];

    fin.close();
    fin.open("inputfile");
    int i=0;
    while(fin >> tmp)
        array[i++]=tmp;

    //do stuff

    delete[] array;
    return 0;
}


I like Duoas' last stament...
You can do all of those things on the fly, just read the data into the first position of some array, then use that to get the current values of min and max, add 1 to count and keep a running sum. (Your instructor will hate you lol)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int main()
{
    int array[2];
    ifstream fin("inputfile");
    
    int max, min, count, sum, avg;

    fin >> max;
    min=max;
    count=1;

    sum=0;
    while(fin >> array[1]){
        if(array[1] > max) max=array[1];
        if(array[1] < min) min=array[1];
        sum+=array[1];
        ++count;
    }

    cout << "min: " << min << endl
            << "max: " << max << endl 
            << "total: " << sum << endl
            << "average: " << sum/count << endl;

    return 0;
}

Last edited on
1
2
3
4
5
6
7
8
#define maxsize 1000000000000 //maybe excessive ;)  ( 1,000,000,000,000 )

int main()
{
    int array[maxsize];
    // ...
    return 0;
}


... You're kidding, right? You're going to allocate approximately 1GB of RAM?

And your third set of codes won't even work right. cin has nothing to do with fin except that they inherit some of the same classes.
Last edited on
lol

I haven't done it that way since high school. Note that I did put a comment next to the def.

But hey, most of the structures I'm working with now can easily grow larger than that (20-30 GB), so it wouldn't be a problem on my machine.

oops, I do that alot ... I'll fix it.
Last edited on
Unfortunately, not all computers have 20-30GB of RAM. Most only have 1-6.
Thanks, I was wondering what the specs for an average computer were...

Also, sizeof(int) is at least 2 and probably 4, so I'm going to allocate approximately 1,000,000,000,000 x 4bytes = 4TB of RAM.
Oh jeez, that's even worse! I thought you were allocating chars.
just use std::vector<int> , search for it in the reference part of this site
You could try using a getline(The C++ variant) to get the number of lines in the program and then allocate an int array of that size. After that you could use getline to store the number on each into a temp string, and then convert that string into an int, and finally store that int into the array based on what line it was gotten from.

I'm don't have the time to write out the code at the moment but I recommend taking a look at
http://www.cplusplus.com/reference/iostream/istream/
Which should help you get the gist of what I am saying.
Take a look at the getline, but make sure it's the C++ string version rather than the old C one, as well as the seekg and tellg.
Thanks for all the info guys, it seems this problem sparked a bit of interest :)
Topic archived. No new replies allowed.