如何停止程序直到用户输入 EOF?

时间:2021-07-10 14:23:03

标签: c eof

我有这个困难的任务,我只需要使用 for 循环..所以我们不允许使用 while 或 do.. while 循环也是 else 语句.. 我试图接受用户输入,直到他/她输入EOF,这样程序就会返回平均数。所以我写了代码并运行它但是每当我输入 ctrl+z (EOF) 程序不会停止甚至返回平均值:(

for (int i = 0; i < 50; i++) {

printf("Please enter employee rank: ");
 scanf("%d", &newnum);

    sumavg += newnum;
    counter++;
    avg = sumavg / counter;

    if (newnum < 8) {
        summ += newnum;
        ccoun++;
        avgle = summ / ccoun;
    }

}

printf("the avg : %d", avg);
printf("\nthe avg : %d \n", avgle);

所以,我更新了代码,这里有一个小问题.. idk 为什么我第一次进入 EOF 时程序没有响应..

for (int i = 0; i < BN; i++) {
printf("Please enter employee rank: ");
result = scanf("%d", &newnum);
    if (result == EOF)
        break;

    sumavg += newnum;
    counter++;
    avg = sumavg / counter;

    if (newnum < 8) {
        summ += newnum;
        ccoun++;
        avgle = summ / ccoun;
    }

enter image description here

3 个答案:

答案 0 :(得分:0)

您可以只检查 scanf() 的返回值。从 scanf() manual,

<块引用>
   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure
   occurs.  EOF is also returned if a read error occurs, in which
   case the error indicator for the stream (see ferror(3)) is set,
   and errno is set to indicate the error.
#include <stdio.h>

int main(void)
{
    int newNum[50];

    for (int i = 0; i < 50; i++)
    {
        int ret = scanf("%d", &newNum[i]);

        if (ret != 1) /* 1 int to read */ 
        {
            if (ret == EOF)
            {
                /* input error might also have occured here, check errno to be sure */
                break;
            }
        }
        /* code */
    }

    return 0;
}

或者直接在for循环中,

for (int i = 0;  i < ARRAY_SIZE && scanf("%d", &newNum[i]) == 1; i++)
{
    /* code */
}

答案 1 :(得分:0)

scanf("%d", &foo) 不会在文件末尾将 EOF 存储在 foo 中。但是您在执行 EOF 时已经准备好检查 scanf,使用它来打破您的循环。

for(....)
 {
    if(scanf(...) != EOF)
      {
         ....
      }
   else
     {
       break;
     }
 }

上面的代码只有一个小问题,它确实检测了 IO 错误和文件结尾,但没有解析错误。最好这样写:

for(int i=0; ...)
  {
    int n;
    int err;
    err = scanf("%d", &n);
    if ( err == 1)
      {
        /* Process input */
        newnum[i] = n;
      }
    else if (err == EOF  && ferror(stdin))
      {
        /* IO error */
        perror ("Failure to read from standard input");
        exit(EXIT_FAILURE);
      }
    else if (err == EOF)
      break;
    else
      {
        /* Handle parse errors */
      }
  }

当然,您必须根据自己的需要进行错误处理。

答案 2 :(得分:-2)

当我需要来自 stdin 的 EOF 时,我运行程序如下。

./a.out <<DATA
1
2
3
4
5
6
7
8
9
10
DATA

这在 Linux 上运行良好。不知道在其他平台上效果如何

相关问题