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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <limits>
#include <iomanip>
enum class Month:unsigned {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC, BAD };
static_assert(static_cast<unsigned>(Month::BAD) == 13);
const std::unordered_map<Month, std::string> monthMap = {
{Month::JAN, "January"},
{Month::FEB, "February"},
{Month::MAR, "March"},
{Month::APR, "April"},
{Month::MAY, "May"},
{Month::JUN, "June"},
{Month::JUL, "July"},
{Month::AUG, "August"},
{Month::SEP, "September"},
{Month::OCT, "October"},
{Month::NOV, "November"},
{Month::DEC, "December"},
{Month::BAD, "Unknown"}
};
struct MonthRainFall {
Month month {};
double rainFall {};
};
Month getMonth(std::string mon)
{
if (const auto ret {std::find_if(monthMap.begin(), monthMap.end(), [&mon](auto m) {return m.second.substr(0, 3) == mon.substr(0, 3); })}; ret != monthMap.end())
return ret->first;
return Month::BAD;
}
std::string monName(Month m)
{
if (const auto ret = monthMap.find(m); ret != monthMap.end())
return ret->second;
return "Unknown";
}
std::istream& operator>>(std::istream& is, MonthRainFall& mrf)
{
std::string mon;
mrf.month = (is >> mon >> mrf.rainFall) ? mrf.month = getMonth(mon) : Month::BAD;
return is;
}
int main()
{
std::ifstream monData("rainfall.txt");
if (!monData.is_open())
return (std::cout << "Cannot open data file\n"), 1;
double sum {}, dataSize {};
double low {std::numeric_limits<int>::max()}, high {std::numeric_limits<int>::min()};
Month lmon {}, hmon {};
for (MonthRainFall mrf; monData >> mrf; ++dataSize) {
sum += mrf.rainFall;
if (mrf.rainFall > high) {
high = mrf.rainFall;
hmon = mrf.month;
}
if (mrf.rainFall < low) {
low = mrf.rainFall;
lmon = mrf.month;
}
}
std::cout << std::fixed << std::setprecision(2);
std::cout << "Sum of all rainFall is " << sum << '\n';
std::cout << "Average rainfall is " << sum / dataSize << '\n';
std::cout << "The month with the lowest rainfall is " << monName(lmon) << '\n';
std::cout << "The month with the highest rainfall is " << monName(hmon) << '\n';
}
|