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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | // Code derived from Stroustrup's PPP2 book
// § 10.11.2 Reading structured values (v2)
// -and beginning on p 370
// note: this is a reworked version of the book's original for this section. the
// primary modification being to use token parsing (similar to chs 6&7) instead
// for retrieving the data from the readings file. one advantage of this new
// design is that overall memory consumption is lower than with the original.
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
void error(string const& s) { throw runtime_error(s); }
void error(string const& s1, string const& s2) { error(s1 + s2); }
void error(string const& s, int const i)
{
ostringstream os;
os << s << ": " << i;
error(os.str());
}
//------------------------------------------------------------------------------
/** run-time checked narrowing cast (type conversion)
*
* @param[in] a object to be typecast
* @return copy of `a`, of the type `R` specified for the cast
* @note throws `std::runtime_error` on information loss
*/
template <class R, class A>
R narrow_cast(A const& a)
{
R r = R(a);
if (A(r) != a)
error("narrow_cast() info loss");
return r;
}
//------------------------------------------------------------------------------
constexpr char number{'8'}; // t.kind==number means that t is a number Token
constexpr char name{'a'}; // name token (eg. dec, year, jan, month, etc.)
//------------------------------------------------------------------------------
class Token {
public:
explicit Token(char const ch) : kind{ch} {}
Token(char const ch, double const val) : kind{ch}, value{val} {}
Token(char const ch, string const& n) : kind{ch}, name{n} {}
char kind = '0';
double value = 0.0;
string name;
};
//------------------------------------------------------------------------------
class Token_stream {
public:
Token_stream();
Token get(ifstream& ist);
void putback(Token const& t);
private:
bool full = false;
Token buffer;
};
//------------------------------------------------------------------------------
Token_stream::Token_stream() : full{false}, buffer{0} {}
//------------------------------------------------------------------------------
// read a token from input stream
Token Token_stream::get(ifstream& ist)
{
if (full) { // check if we already have a Token ready
full = false;
return buffer;
}
char ch;
ist >> ch;
if (ist.eof())
return Token{'E'};
// clang-format off
switch (ch) {
case '{':
case '}':
case '(':
case ')':
return Token{ch};
break;
case '.': case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
ist.putback(ch); // put digit back into the input stream
double val;
ist >> val;
return Token{number, val};
break;
}
default:
if (isalpha(ch)) {
string s;
s += ch;
while (ist.get(ch) && isalpha(ch))
s += ch;
ist.putback(ch);
return Token{name, s};
}
error("Bad token");
return Token{'K'}; // invalid, shouldn't reach here
}
// clang-format on
}
//------------------------------------------------------------------------------
// put token back into stream
void Token_stream::putback(Token const& t)
{
if (full)
error("putback() into a full buffer");
buffer = t;
full = true;
}
//------------------------------------------------------------------------------
Token_stream ts;
//------------------------------------------------------------------------------
const vector<string> month_input_tbl{"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"};
// is s the name of a month? If so return its index [0:11] otherwise –1
int month_to_int(string const& s)
{
for (int i = 0; i < 12; ++i)
if (month_input_tbl[i] == s)
return i;
return -1;
}
const vector<string> month_print_tbl{
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
// months [0:11]
string int_to_month(int const i)
{
if (i < 0 || 12 <= i)
error("bad month index");
return month_print_tbl[i];
}
//------------------------------------------------------------------------------
struct Reading {
int day;
int hour;
double temperature;
};
// a rough test
bool is_valid(Reading const& r)
{
constexpr int implausible_min{-200};
constexpr int implausible_max{200};
if (r.day < 1 || 31 < r.day) // naive
return false;
if (r.hour < 0 || 23 < r.hour)
return false;
if (r.temperature < implausible_min || implausible_max < r.temperature)
return false;
return true;
}
//------------------------------------------------------------------------------
constexpr int nada{-1};
struct Month {
explicit Month(int const m) : month{m} {}
int month{nada}; // [0:11] January is 0
vector<Reading> rdgs; // Reading's contain their own day/hour info
};
struct Year {
explicit Year(int const y) : year{y} {}
int year{nada}; // positive == A.D.
vector<Month> months;
};
//------------------------------------------------------------------------------
void readings(ifstream& ist, vector<Reading>& rdgs)
{
Token t = ts.get(ist);
while (true) {
switch (t.kind) {
case '(': {
double day, hr, temp;
t = ts.get(ist);
if (t.kind != number)
error("day expected in readings()");
day = t.value;
t = ts.get(ist);
if (t.kind != number)
error("hour expected in readings()");
hr = t.value;
t = ts.get(ist);
if (t.kind != number)
error("temp expected in readings()");
temp = t.value;
t = ts.get(ist);
if (t.kind != ')')
error("')' expected in readings()");
// get a clean r each time around
Reading const r{narrow_cast<int>(day), narrow_cast<int>(hr), temp};
//
// note: code could be written to allow invalid or duplicate readings to
// be accounted for during this function (or in months()) if so desired.
//
// otherwise, invalid readings are simply ignored here, and are not
// written out to the month's readings container (while duplicates are).
//
if (is_valid(r))
rdgs.push_back(r);
break;
}
default: ts.putback(t); return;
}
t = ts.get(ist);
}
}
//------------------------------------------------------------------------------
void months(ifstream& ist, vector<Month>& mns)
{
Token t = ts.get(ist);
while (true) {
switch (t.kind) {
case '{': {
t = ts.get(ist);
if (t.kind != name)
error("month_lbl expected");
t = ts.get(ist);
if (t.kind != name)
error("month_name expected");
string const month_nm = t.name;
// get all readings, for this month:
vector<Reading> rdgs; //
readings(ist, rdgs); //
t = ts.get(ist);
if (t.kind != '}')
error("'}' expected in months()");
// get a clean m each time around
Month m{month_to_int(month_nm)};
m.rdgs = rdgs;
mns.push_back(m);
break;
}
default: ts.putback(t); return;
}
t = ts.get(ist);
}
}
//------------------------------------------------------------------------------
void years(ifstream& ist, vector<Year>& ys)
{
Token t = ts.get(ist);
while (true) {
switch (t.kind) {
case '{': {
t = ts.get(ist);
if (t.kind != name)
error("year_lbl expected");
t = ts.get(ist);
if (t.kind != number)
error("year_num expected");
double const yr = t.value;
// get all months with readings, for this year:
vector<Month> mns; //
months(ist, mns); //
t = ts.get(ist);
if (t.kind != '}')
error("'}' expected in years()");
// get a clean y each time around
Year y{narrow_cast<int>(yr)};
y.months = mns;
ys.push_back(y);
break;
}
case 'E':
return; // all data is parsed (eof)
break;
default: ist.clear(ios_base::failbit); error("unknown error in years()");
}
t = ts.get(ist);
}
}
//------------------------------------------------------------------------------
void print_year(ostream& ost, Year const& y)
{
ost << "\nYEAR: " << y.year << '\n';
for (auto const& m : y.months) {
ost << " MONTH: " << int_to_month(m.month) << '\n';
auto rdgs_sort = m.rdgs; // we'll use a sortable copy of month's readings
// 1st pass, sorted by-hour
sort(begin(rdgs_sort), end(rdgs_sort),
// note: this is a lambda expression (§15.3.3)
[](Reading const& a, Reading const& b) { return (a.hour < b.hour); });
// 2nd pass, sorted by-day
sort(begin(rdgs_sort), end(rdgs_sort),
[](Reading const& a, Reading const& b) { return (a.day < b.day); });
for (auto const& r : rdgs_sort) {
ost << " (" << r.day //
<< ", " << r.hour //
<< ", " << r.temperature //
<< ")\n";
}
}
}
//------------------------------------------------------------------------------
int main()
try {
// open an input file:
cout << "Please enter input file name (eg, odd_format.txt ): ";
string iname;
cin >> iname;
ifstream ist{iname};
if (! ist)
error("can't open input file ", iname);
ist.exceptions(ist.exceptions() | ios_base::badbit); // throw for bad()
// open an output file:
cout << "Please enter output file name: ";
string oname;
cin >> oname;
if (oname == iname)
error("this would overwrite the original file");
ofstream ost{oname};
if (! ost)
error("can't open output file ", oname);
// read an arbitrary number of years from input stream:
vector<Year> ys; //
years(ist, ys); //
// write formatted data to output stream:
cout << "read " << ys.size() << " years of readings\n";
for (auto const& y : ys)
print_year(ost, y);
} catch (exception const& e) {
cerr << "error: " << e.what() << '\n';
return 1;
} catch (...) {
cerr << "Oops: unknown exception!\n";
return 2;
}
|
build & run:
g++ -std=c++20 -O2 -Wall -pedantic ./ch_10/main_p370_v2.cpp && ./a.out