Cleaning up little temperature converter program

based a bit on how the example qsort program was written, plus fixing a
pedantic error.
This commit is contained in:
Dan Buch 2012-05-29 15:02:16 -04:00
parent 02699f591f
commit 13257b1ecc

View File

@ -1,6 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
double c2f(double celsius) {
@ -13,43 +14,44 @@ double f2c(double fahrenheit) {
}
int usage(const char *msg) {
printf("Usage: temperatures <temp>[fFcC]\n");
void usage(const char *prog, const char *msg) {
fprintf(stderr, "Usage: %s <temp>[fFcC]\n", prog);
if (msg != NULL) {
printf("%s\n", msg);
fprintf(stderr, "%s\n", msg);
}
return 1;
}
int main(int argc, char * argv[]) {
if (argc < 2) {
usage(NULL);
return 2;
}
const char * prog = basename(argv[0]);
int ret;
char msg[255];
double temp;
char scale = '\0';
const char *in_fmt = "%lf%c";
const char *out_fmt = "%.2lf%c\n";
const char *temp_string;
if (argc < 2) {
usage(prog, NULL);
exit(EXIT_FAILURE);
}
if (((int)strlen(argv[1]) == 1) && (argv[1][0] == '-')) {
ret = fscanf(stdin, in_fmt, &temp, &scale);
} else {
const char * temp_string = argv[1];
temp_string = argv[1];
ret = sscanf(temp_string, in_fmt, &temp, &scale);
}
if ((ret == 0) || (ret == EOF)) {
usage("No temperature provided!");
return 1;
usage(prog, "No temperature provided!");
exit(EXIT_FAILURE);
}
if (ret == 1) {
usage("No scale provided!");
return 1;
usage(prog, "No scale provided!");
exit(EXIT_FAILURE);
}
switch (scale) {
@ -63,9 +65,9 @@ int main(int argc, char * argv[]) {
break;
default:
sprintf(msg, "Unknown scale: '%c'", scale);
usage(msg);
usage(prog, msg);
break;
}
return 0;
exit(EXIT_SUCCESS);
}