-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrational-cmdline.cpp
67 lines (58 loc) · 1.25 KB
/
rational-cmdline.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <sstream>
#include <string>
#include "rational.h"
/* Basic command line interface for experimenting with rational arithmetic.
* Three command-line arguments are expected (in addition to the implicit file path):
*
* 1st - A string representation of a rational number (see rational.h)
*
* 2nd - One of the four operators: + , - , * , /
*
* 3rd - A string representation of a rational number (see rational.h)
*
* For example: ./rational-cmdline "1/3" "*" "4/9"
*/
using namespace ExactArithmetic;
using std::cout;
using std::endl;
int main(int argc, const char * argv[])
{
// Remember, argv[0] is the filename
if (argc != 4)
{
cout << "Incorrect number of arguments, expected 3: Rational Operator Rational" << endl;
cout << "For example: " << argv[0] << " \"1/3\" \"*\" \"4/9\"" << endl;
return 1;
}
std::string op = argv[2];
std::istringstream xstr(argv[1]);
std::istringstream ystr(argv[3]);
Rational x, y;
xstr >> x;
ystr >> y;
Rational result;
if (op == "+")
{
result = x + y;
}
else if (op == "-")
{
result = x - y;
}
else if (op == "*")
{
result = x * y;
}
else if (op == "/")
{
result = x / y;
}
else
{
cout << "Unrecognised operator" << endl;
return 1;
}
cout << result << endl;
return 0;
}