-
Notifications
You must be signed in to change notification settings - Fork 2
/
flag_example.cpp
60 lines (52 loc) · 1.05 KB
/
flag_example.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
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <getopt.h>
using namespace std;
void print_usage() {
cout << "Usage: ./temperature -c <temp> | temp -f <temp>" << endl;
exit(2);
}
void print_fahrenheit(float temp) {
float f = ((temp*9)/5)+32;
cout << temp << " centigrade is " << f << " fahrenheit" << endl;
}
void print_centigrade(float temp) {
float c = ((temp-32)*5)/9;
cout << temp << " fahrenheit is " << c << " centigrade" << endl;
}
int main(int argc, char **argv) {
cout << fixed;
cout << setprecision(2);
if (argc < 2) {
print_usage();
}
int option;
int cflag=0;
int fflag=0;
while ((option = getopt(argc, argv, "c:f:")) != -1) {
switch (option) {
case 'c' :
if (cflag) {
print_usage();
} else {
cflag++;
fflag++;
}
print_fahrenheit(atof(optarg));
break;
case 'f' :
if (fflag) {
print_usage();
} else {
cflag++;
fflag++;
}
print_centigrade(atof(optarg));
break;
default :
cout << "Error" << endl;
}
}
return 0;
}