This is my code so far
#include<fstream>
#include<iostream>
#include<cstdlib>
#include<stdlib.h>
using namespace std;
const int MAX_GENERATED = 100;
void fillArray(int a[], int size, int& numberUsed); //prototype
int main ()
{
int array[MAX_GENERATED], numberUsed;
fillArray (array, MAX_GENERATED, numberUsed);
getchar ();
getchar ();
return 0;
}
void fillArray( int array[], int size, int& numberUsed)
{
ifstream inStream;
string fileName;
cout << "What file would you like to work with?" << endl;
cout << "Remember to include the file extension." << endl;
cin >> fileName;
inStream.open(fileName.c_str()); //to connect with file
int next, index = 0;
inStream >> next;
while (index < size) //loop fills array
{
array[index] = next;
cout << array[index] << endl;
index++;
inStream >> next;
} //end while loop
numberUsed = index;//maybe can do something with this
//might need 2d array??
}
It reads the input from a text file with one number per line with a maximum of 100 numbers in the file. These were numbers from -20 to 20 and were randomly generated.
I now have to display each number and the number of times it appears in the input file
It has to look something like this:
--------------
N COUNT
--------------
-12 4
3 3
4 2
1 4
-1 1
2 2
--------------
Total = 16
--------------
The problem with the code as it is, is that there are 20 numbers in the file, the last one being a randomly generated 15. When the program displays the numbers it does fine, but displays the number "15" eighty times. I want to know how to fix this, if possible.
Also, how may I go about counting the number of times each number appears?
I know I can do an if statement that if the number is -20, increment a counter and do that for up to 20. However, this method is tedious and I don't think it is desired for this.
I appreciate any help at all on this, I hope I've given enough information.