More goofing around with temperature conversion

for make near-mindless C practice.
This commit is contained in:
Dan Buch 2012-05-28 13:13:07 -04:00
parent de38919448
commit c75da5dba7

View File

@ -1,5 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h>
double c2f(double celsius) { double c2f(double celsius) {
@ -12,36 +13,57 @@ double f2c(double fahrenheit) {
} }
int die_usage(const char *msg) { int usage(const char *msg) {
printf("Usage: temperatures <temp>[fFcC]\n"); printf("Usage: temperatures <temp>[fFcC]\n");
if (msg != NULL) {
printf("%s\n", msg); printf("%s\n", msg);
exit(1); }
return 1;
} }
int main(int argc, char * argv[]) { int main(int argc, char * argv[]) {
if (argc < 2) { if (argc < 2) {
die_usage(""); usage(NULL);
return 2;
} }
int ret;
char msg[255]; char msg[255];
double temp; double temp;
char scale = '\0'; char scale = '\0';
const char * temp_string = argv[1]; const char *in_fmt = "%lf%c";
const char *out_fmt = "%.2lf%c\n";
if (((int)strlen(argv[1]) == 1) && (argv[1][0] == '-')) {
ret = fscanf(stdin, in_fmt, &temp, &scale);
} else {
const char * temp_string = argv[1];
ret = sscanf(temp_string, in_fmt, &temp, &scale);
}
if ((ret == 0) || (ret == EOF)) {
usage("No temperature provided!");
return 1;
}
if (ret == 1) {
usage("No scale provided!");
return 1;
}
sscanf(temp_string, "%lf%c", &temp, &scale);
switch (scale) { switch (scale) {
case 'c': case 'c':
case 'C': case 'C':
printf("%.2lf\n", c2f(temp)); printf(out_fmt, c2f(temp), 'F');
break; break;
case 'f': case 'f':
case 'F': case 'F':
printf("%.2lf\n", f2c(temp)); printf(out_fmt, f2c(temp), 'C');
break; break;
default: default:
sprintf(msg, "Unknown scale '%c'", scale); sprintf(msg, "Unknown scale: '%c'", scale);
die_usage(msg); usage(msg);
break; break;
} }