I have to write a program for a Lab exercise that counts the occurrence of integers in an array read from a text file. Here's the what my professor is asking for:
Write a program the reads a file name as input. The file contains a number of integer numbers (only integers). Your program should read all these numbers and print out the number of occurrences of each number to both the screen and another file called “result.txt”. For example, if the file contains 10, 20, 450, 40, 30, 40, 50, 10, 40, 20, then your program will write both onto screen and “result.txt” the following:
Number 10 occurs 2 times
Number 20 occurs 2 times
Number 450 occurs 1 times
Number 40 occurs 3 times
Number 30 occurs 1 times
Number 50 occurs 1 times
I got it to where each integer entry in the text file gets its own index in the array, but I am completely stuck when it comes to displaying how many times each integer appears. If it matters, I'm using the example integers from the prompt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
char input[32];
ifstream in_stream;
in_stream.open("input.txt");
cout << "Enter the file that you would like to open: ";
cin >> input;
int integer[100], i = 0;
for (i = 0; i < 100; i++)
in_stream >> integer[i];
return 0;
}
I will presume that you are not permitted to use a standard library histogram structure, like std::map.
You will need a struct (or, if you haven't done that yet either, two arrays) containing the number and the number of times that number has appeared.
You will need a function to find the index of a number in the array, so that you can:
- add a number to the array(s) if it is not already present
- increment a number's count if it is already present