-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
60 lines (47 loc) · 1.47 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <fstream>
#include <iostream>
#include <vector>
#include "statistics.h"
// Function declaration
std::vector<int> read_numbers(const std::string& filename);
// Main function
int main() {
std::string f_name;
std::cout << "Specify the name of the file containing the numbers: ";
std::cin >> f_name;
try {
std::vector<int> numbers = read_numbers(f_name);
double mean = calculate_mean(numbers);
double median = calculate_median(numbers);
std::vector<int> modes = calculate_mode(numbers);
std::cout << "Mean: " << mean << '\n'
<< "Median: " << median << '\n'
<< "Mode: ";
for (int mode : modes) {
std::cout << mode << " ";
}
std::cout << std::endl;
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
// Function: Open file and populate a vector.
std::vector<int> read_numbers(const std::string& filename) {
std::ifstream inFile(filename);
if (!inFile) {
throw std::runtime_error("Could not open the given file.");
}
std::vector<int> numbers;
int number;
while (inFile >> number) {
numbers.push_back(number);
}
if (numbers.empty()) {
// No integers into 'numbers', ergo the file data was not correct.
throw std::runtime_error(
"The file is empty or contains non-numeric data.");
}
inFile.close();
return numbers;
}