write random hour + temperature pairs [fahrenheite + celsius indicator]

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

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PPP
// Chapter 10 Exercise 4.0

#include "std_lib_facilities.h"

struct Reading {
int hour;
double temperature;
char suffix;
Reading(int h, double t, char s) :hour(h), temperature(t), suffix(s) {}
};

ostream& operator<<(ostream& os, Reading& _temps) {
os << _temps.hour << " " << _temps.temperature << " " << _temps.suffix << endl;
return os;
}

vector<Reading> temps;

string oname = "raw_temps.txt";
ofstream ost(oname);

int random_temperatur(int seed, int max) {
srand(seed);
return randint(max);
}

char random_suffix(int seed) {
srand(seed);
if (randint(100) <= 50) {
return ‘c’;
}
else {
return ‘f’;
}
}

void fill_vector(vector<Reading>& _temps) {
cout << "Generating Data." << endl;
int h;
double t;
char s;
int temp_hour = 0;

for (int i = 0; i < 50; i++) {
if (!(i % 24)) {
temp_hour = 0;
}

h = temp_hour;
t = random_temperatur(0, 90);
s = random_suffix(1);

_temps.push_back(Reading{ h, t, s});
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 c
1 1 c
2 72 c
3 65 c
4 49 f
5 48 c
6 67 f
7 20 c
8 76 f
9 36 c
10 15 c
11 16 c
12 34 c
13 37 f
14 79 f
15 60 f
16 15 c
17 1 c
18 84 c
19 79 f
20 0 c
21 86 f
22 76 c
23 73 c
0 74 f
1 22 f
2 28 f
3 30 c
4 36 c
5 0 c
6 60 f
7 78 f
8 56 c
9 51 f
10 40 f
11 52 f
12 15 f
13 47 f
14 59 f
15 82 f
16 77 c
17 46 f
18 1 c
19 0 c
20 1 c
21 2 c
22 15 c
23 36 c
0 87 c
1 29 c

Leave a Reply