我将如何使用 EOF 结束以下代码中的输入?

How would I use EOF to end input in the following code?

我目前正在从事一个计算机科学项目,但在尝试完成最后的步骤时遇到了困难。到目前为止它非常混乱,但代码基本上采用前两个值作为 x 和 y 坐标,并使用它们来产生总距离。它还使用第三个点来计算总的上坡和下坡坡度。我已经让这些部分正常工作,但是分配声明:您应该使用 scanf 读取数据直到 EOF 发生,这可以通过检查 scanf 的 return 值来检测。 我想知道我将如何实现这一目标?目前我的 do-while 循环的约束是一旦它 = EOF 它将终止,但是这会导致代码在任何 -1 出现时终止。 这是代码:

   #include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
    double a;
    double total;
    double up;
    double b;
    double c;
    double d;
    double down;
    double zc;
    double yes;
    double m;
    double n;
    double m2;
    double n2;
    double o;
    double p;
    double q;
    double xc;
    double yc;
    int i = 1;
    xc = 1000;
    yc = 1000;
    total = 0;
    down = 0;
    scanf("%lf", &c);
    do 
    {
        if (i == 1) {
            a = c;
            scanf ("%lf", &c);
            i += 1;
        }
        else if (i == 2) {
            b = c;
            scanf ("%lf", &c);
            i += 1;
        }

        else if (i ==3) {
            d = c;
            if (xc == 1000 && yc == 1000) {
                i = 4;
            }
            else if (xc != 1000) {
                i = 5;
            }
        }


        else if (i == 4) {
                if (d > zc) {
                    yes = d - zc;
                    up = yes/p;
                    if (up > total) {
                        total = up;
                    }
            }
                if (d < zc) {
                    yes = d - zc;
                    up = yes/p;
                     if (up < 0) {
                        up = up *-1;
                    }
                    if (up > down) {
                        down = up;

            }
        }
            xc = b;
            yc = a;
            zc = d;
            scanf ("%lf", &c);
            i = 1;
        }

        else if (i == 5) {
            m = (xc - b);
            n = (yc - a);
            m2 = m*m;
            n2 = n*n;
            o = m2 + n2;
            p = sqrt(o);
            q = q + p;
            i = 4;
        }
    }

    while (c != EOF && i <= 5);


    printf ("Total distance: %.1lf\n", q);
    printf ("Maximum uphill gradient: %.3lf\n", total);
    printf ("Maximum downhill gradient: %.3lf\n", down);
    return EXIT_SUCCESS;
}

并给出以下输入:

0.0 0.0 0.0
0.0 3.0 1.0
1.0 3.0 2.0
1.0 5.0 -1.0
4.0 5.0 -1.0

应该return:

Total distance: 9.0
Maximum uphill gradient: 1.000
Maximum downhill gradient: 1.500

您可以像这样存储 return scanf 的值 check=scanf("%lf", &c); 并且 while(check != EOF && i <= 5); check变量的类型必须是int。

您可以检查函数 scanf() 的 return 值。例如: scanf("%d %d",&a,&b);.

  1. 如果读取ab成功,它将return2
  2. 如果只读取a成功,会return1.
  3. 如果读取'a'失败,现在b是无关的,例如:a不是int,它将return 0.
  4. 如果在 scanf() 时获取文件末尾,它将 return EOF.

希望对您有所帮助