sort and count numbers

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 11 Exercise 16
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PPP
//	Chapter 11 Exercise 16

#include "std_lib_facilities.h"

int main()
try
{
	cout << "enter name for input file" << endl;
	string iname = "input/";
	string itemp;
	cin >> itemp;
	iname += itemp;
	ifstream ifs{ iname };
	if (!ifs) { cout << "could not open input file." << endl; }

	cout << "enter name for output file" << endl;
	string oname = "output/";
	string otemp;
	cin >> otemp;
	oname += otemp;
	ofstream ofs{ oname };
	if (!ofs) { cout << "could not open output file." << endl; }

	vector<double> nums;
	for (double d; ifs >> d;) {
		nums.push_back(d);
	}

	sort(nums);

	for (int i = 0; i < nums.size(); i++) {
		cout << i << " " << nums[i] << endl;
	}

	int count = 1;

	for (int i = 1; i < nums.size(); i++) {
		if (nums[i] == nums[i - 1]) {
			count++;
		}
		else {
			ofs << nums[i - 1];
			if (count > 1) {
				ofs << " " << count << endl;
				count = 1;
			}
			else {
				ofs << endl;
			}
		}
		if (i == nums.size() - 1 && nums[i] == nums[i - 1]) {
			if (count == 1) {
				count++;
			}
			ofs << nums[i];
			ofs << " " << count << endl;
			ofs << endl;
		}
	}

	keep_window_open();
}
catch (runtime_error e) {
	cout << e.what() << endl;
	keep_window_open();
}
catch (...) {
	cout << "Exiting" << endl;
	keep_window_open();
}
Output:
enter name for input file
p409_16_random_num.txt
enter name for output file
p409_16_random_num_out.txt
Please enter a character to exit
Input-File: p409_16_random_num.txt
58
32
50
80
54
13
24
82
52
17
17
8
87
12
35
42
88
72
46
91
69
60
84
55
99
21
6
25
53
13
75
83
94
2
71
35
85
50
71
99
60
47
68
29
100
54
45
66
4
98
57
13
23
3
8
9
47
67
17
52
5
60
73
28
18
45
5
7
99
78
78
17
3
87
37
33
83
92
83
99
45
75
28
73
66
44
11
73
9
24
29
39
52
99
24
95
8
91
90
99
100
Input-File: p409_16_random_num_out.txt
2
3 2
4
5 2
6
7
8 3
9 2
11
12
13 3
17 4
18
21
23
24 3
25
28 2
29 2
32
33
35 2
37
39
42
44
45 3
46
47 2
50 2
52 3
53
54 2
55
57
58
60 3
66 2
67
68
69
71 2
72
73 3
75 2
78 2
80
82
83 3
84
85
87 2
88
90
91 2
92
94
95
98
99 6
100 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.