Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my C program can't read data from file using "<" character

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading