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?
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.
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.
int main()
{
int *array;
int tmp, count;
ifstream fin("inputfile");
while(fin >> tmp)
count++;
array = newint[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)
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.