Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 10 Exercise 2
Using std_lib_facilities.h by Bjarne Stroustrup.
[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PPP
// Chapter 10 Exercise 2
#include "std_lib_facilities.h"
struct Reading {
int hour;
double temperature;
};
ostream& operator<<(ostream& os, Reading& _temps) {
os << _temps.hour << " " << _temps.temperature << endl;
return os;
}
vector<Reading> temps;
string oname = "output/raw_temps.txt";
ofstream ost(oname);
void fill_vector(vector<Reading>& _temps) {
cout << "Generating Data." << endl;
int h;
double t;
int temp_hour = 0;
for (int i = 0; i < 50; i++) {
if (!(i % 24)) {
temp_hour = 0;
}
h = temp_hour;
t = randint(90);
_temps.push_back(Reading{ h, t });
temp_hour++;
}
}
void write_file(vector<Reading>& _temps) {
cout << "Writing File." << endl;
for (int i = 0; i < temps.size(); i++) {
ost << _temps[i];
}
cout << "Done!" << endl;
}
int main()
try
{
fill_vector(temps);
write_file(temps);
keep_window_open();
}
catch(runtime_error e) {
cout << e.what() << endl;
keep_window_open();
}
catch (…) {
cout << "Exiting" << endl;
keep_window_open();
}
[/code]
Output: Generating Data. Writing File. Done! Please enter a character to exit
Output-File raw_temps.txt: 0 78 1 14 2 1 3 15 4 72 5 20 6 65 7 54 8 49 9 67 10 48 11 73 12 67 13 49 14 20 15 42 16 76 17 38 18 36 19 40 20 15 21 87 22 16 23 51 0 34 1 63 2 37 3 48 4 79 5 41 6 60 7 21 8 15 9 51 10 1 11 41 12 84 13 13 14 79 15 38 16 0 17 16 18 86 19 88 20 76 21 50 22 73 23 77 0 74 1 44