forked from AfikPeretz/NumberWithUnits.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Demo.cpp
48 lines (40 loc) · 1.45 KB
/
Demo.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
/**
* Demo file for the exercise on numbers with units
*
* @author Erel Segal-Halevi
* @since 2019-02
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
#include "NumberWithUnits.hpp"
using namespace ariel;
int main() {
ifstream units_file{"units.txt"};
NumberWithUnits::read_units(units_file);
NumberWithUnits a{2, "km"}; // 2 kilometers
cout << a << endl; // Prints "2[km]".
cout << (-a) << endl; // Prints "-2[km]"
cout << (3*a) << endl; // Prints "6[km]"
NumberWithUnits b{300, "m"}; // 300 meters
cout << (a+b) << endl; // Prints "2.3[km]". Note: units are determined by first number (a).
cout << (b-a) << endl; // Prints "-1700[m]". Note: units are determined by first number (b).
cout << boolalpha; // print booleans as strings from now on:
cout << (a>b) << endl; // Prints "true"
cout << (a<=b) << endl; // Prints "false"
cout << (a==NumberWithUnits{2000, "m"}) << endl; // Prints "true"
istringstream sample_input{"700 [ kg ]"};
sample_input >> a;
cout << a << endl; // Prints "700[kg]"
cout << (a += NumberWithUnits{1, "ton"}) << endl; // prints "1700[kg]"
cout << a << endl; // Prints "1700[kg]". Note that a has changed.
try {
cout << (a+b) << endl;
} catch (const std::exception& ex) {
cout << ex.what() << endl; // Prints "Units do not match - [m] cannot be converted to [kg]"
}
cout << "End of demo!" << endl;
return 0;
}