The program could also be written to take the input data from the command line. This would then be run by typing
program 1200to convert 1200 lbs
The program looks like this
main(argc, argv)
int argc;
char *argv[];
{ int pounds;
if(argc != 2)
{ printf("Usage: convert weight_in_pounds\n");
exit(1);
}
sscanf(argv[1], "%d", £s); /* Convert String to int */
printf(" US lbs UK st. lbs INT Kg\n");
print_converted(pounds);
}
print_converted(pounds)
int pounds;
/* Convert U.S. Weight to Imperial and International
Units. Print the results */
{ int stones = pounds / 14;
int uklbs = pounds % 14;
float kilos_per_pound = 0.45359;
float kilos = pounds * kilos_per_pound;
printf(" %3d %2d %2d %6.2f\n",
pounds, stones, uklbs, kilos);
}
Note that the main function definition has changed so that it takes two arguments, argc is a count of the number of arguments, and argv is an array of strings containing each of the arguments. The system sets these up when the program is run.
Some other new concepts are introduced here.
if(argc != 2) Checks that the typed command has two elements, the command name and the weight in pounds.
exit(1); Leave the program. The argument 1 is a way of telling the operating system that an error has occurred. A 0 would be used for a successful exit.
sscanf(argv[1], "%d", £s)
The argument is stored in argv[1] as a string. The program requires an integer value.
sscanf works like scanf, but reads from a string instead of from the terminal.
This is a good method of converting string format data to numeric values.
The rest of the program is the same as the previous one.