Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #define N 100
- using namespace std;
- typedef struct myrec { // record definition
- int item;
- int cnt;
- } rec;
- typedef rec hist[N]; // array of records definition
- // prototypes
- void loadHistogram(hist, int&);
- void printHistogram(hist, int);
- void printHistToFile(hist, int);
- int exist(hist, int, int);
- int main() {
- int cap;
- hist h;
- loadHistogram(h, cap);
- cout << "Print: \n\n";
- printHistogram(h, cap);
- printHistToFile(h, cap);
- return 0;
- }
- // returns -1 if the element 'element' doesn't exist in the array
- // otherwise it returns the position of the element
- int exist(hist h, int cap, int element) {
- int i = 0;
- while ((h[i].item != element) && (i < cap))
- i++;
- if (i == cap)
- return -1;
- else
- return i;
- }
- void loadHistogram(hist h, int &cap) {
- fstream fin;
- fin.open("fin.txt", ios::in);
- if (!fin.is_open()) {
- cout << "File not found...\n";
- } else {
- int newcap = 0; // number of the item without duplicates
- while (!fin.eof()) {
- int e;
- fin >> e; // read an element from file
- if (exist(h, newcap, e) == -1) { // if not exists, it is a new item
- h[newcap].item = e; // save the new item in a new position
- h[newcap].cnt = 1; // set to 1 the counter
- newcap++;
- } else // otherwise, if it exists, so just increase the counter
- h[exist(h, newcap, e)].cnt++;
- }
- // set the array cap with the real number of items (without duplicates)
- cap = newcap;
- }
- fin.close();
- }
- // print the array of structures on the video stream
- void printHistogram(hist h, int cap) {
- for (int i = 0; i < cap; i++) {
- cout << h[i].item << "\t\t" << h[i].cnt << " ";
- for (int j = 0; j < h[i].cnt; j++)
- cout << "o";
- cout << endl;
- }
- }
- // print the array of structures on the file stream
- void printHistToFile(hist h, int cap) {
- fstream fout;
- fout.open("fout.txt", ios::out);
- for (int i = 0; i < cap; i++) {
- fout << h[i].item << "\n";
- fout << h[i].cnt << "\n";
- }
- fout.close();
- }
Advertisement
Add Comment
Please, Sign In to add comment