为什么我的 C 程序无法使用“<”字符从文件中读取数据

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

我正在以批处理模式编写演示 C 应用程序,它将尝试从文件中读取作为输入。 命令是:metric <mydata

C 源文件是:

/* 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);
}

文件“mydata”仅包含一个整数 100

当我运行命令metric <mydata。输出是:

The distance in miles is 0.00.
That equals 0.00 kilometers.

知道哪里出了问题吗?

你误读了文档:而不是 scanf("1f", &miles); 你应该写:

scanf("%lf", &miles);

测试 scanf() 的 return 值可以避免在转换失败时发生未定义的行为,并有助于检测此错误。还建议在编译器 (gcc -Wall -Wextra -Werror) 中启用所有警告以避免愚蠢的错误。

这是修改后的版本:

/* 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;
}