PDA

View Full Version : reading input into an array


seijuro
04-16-04, 03:07 AM
I was wondering how I would go about reading in an input file of numbers and storing it in an array so that I could find out how many times a number occured. So far all I have is a way to read in the numbers and sum them up, but I don't know how to put it in an array. So far I have this..any help would be appreciated

int num = 0, sum = o, count = o;
ifstream fin("numbers.txt");
if(fin.fail())
{
cout << "File does not exist" << endl;
exit(EXIT_FAILURE);
}
fin >> num;
while(!fin.eor())
{
sum += num;
count++;
fin >> num;
}
fin.close();

ofstream fout("results.txt");
fout << count << endl;

if(fout.fail())
{
cout << "fout fail" << endl;
exit(EXIT_FAILURE);
}
fout.close();

hyjacked
04-17-04, 01:39 AM
arrays are similar to variables, except that you must refer to a specific place in the arrray when you want to save a value.

for example
int values[10];
would give you an array, called values, that can hold 10 elements, numbered 0 through 9.
in order to access the first element, you would refer to it by values[0], in order to refer to the fifth element, you would refer to it by values[4].

you can also cycle through an array by using a loop, and use the loop variable, call it i, as the index of the array, ie: values[i]

hope this has been helpful.
best of luck.

seijuro
04-17-04, 07:18 AM
I understand how to use arrays and how I can use the [] to access individual elements in an array. What I would like to know is there a way to count the occurences of each number in an array and then display it without writing too much code?

EvilHaider
04-19-04, 08:18 PM
To figure out how many times each number occurs you basically have to run through the entire array and 'note' the occurrances. For example if your array consists of numbers between 0 and 9. You could make 10 variables of type int initialized to 0: a,b,c...i,j. where a corresponds to 0, b to 1, and so on. As you are running through the array, you check the number, if it's 1, you increment b; if its 3, you increment d, and so on. When you're done with the array you will have the 10 variables that have a count of how many times the corresponding number appears in your array. This is somewhat messy though. An alternative approach would be to utilize a two dimensional array in place of the 10 variables, which would clean it up a bit - especially if you dont know ahead of time what numbers to expect in your array and have to deal with whatever number is presented (for example if the number 13 is found, how do u deal with that?). Does this help?

hyjacked
04-20-04, 01:22 AM
I'd say go with the 2d array approach, it's a lot neater than having variables.

for every element, check if it's in the list, if it is, increment the second cell for that number, if it is not, add it to the end of the array, and increment it's number.

In the end this should give you a list of distince elements, along with how many times they occured.