I am writing a demo C application in batch mode, which will try to read from a file as input.
The command is : metric <mydata
The C source file is:
/* Converts distances from miles to kilometers. */
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constants */
int main(void)
{
double miles, /* distance in miles */
kms; /* equivalent distance in kilometers */
/* Get and echo the distance in miles. */
scanf("1f", &miles);
printf("The distance in miles is %.2f.\n", miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %.2f kilometers.\n", kms);
return (0);
}
The file "mydata" contains simply an integer 100
When I run the command metric <mydata. The output is:
The distance in miles is 0.00.
That equals 0.00 kilometers.
Is there any idea what’s wrong?
>Solution :
You misread the doc, instead of scanf("1f", &miles); you should write:
scanf("%lf", &miles);
Testing the return value of scanf() avoids undefined behavior when the conversion fails and would have helped detect this error. Enabling all warnings in your compiler (gcc -Wall -Wextra -Werror) is also recommended to avoid silly mistakes.
Here is a modified version:
/* Converts distances from miles to kilometers. */
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constants */
int main(void) {
double miles; /* distance in miles */
double kms; /* equivalent distance in kilometers */
/* Get and echo the distance in miles. */
if (scanf("%lf", &miles) != 1) {
fprintf(stderr, "invalid input\n");
return 1;
}
printf("The distance in miles is %.2f.\n", miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %.2f kilometers.\n", kms);
return 0;
}