繁体   English   中英

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

[英]How to stop the program until the user input 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;
    }

在此处输入图片说明

EOF 不是字符,不能存储在字符变量中。

当 scanf() 遇到 ctrl+D 或 ctrl+Z 时,它返回 EOF(这取决于你在什么平台上......在 DOS/Windows 上,Ctrl+Z 将发送 EOF;在 Unix 类型系统上,通常是 Ctrl+ D 信号 EOF)。

您的第一次检查没问题,但在读取时稍作更改以将 resultOfScanf 存储在变量中。 然后检查 scanf 的返回值是否为 EOF - 为此使用 break 语句更改后面的条件。

您可以只检查scanf()的返回值。 scanf()手册

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

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

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

自然地,您必须使错误处理适合您的需要。

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

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

这在 Linux 上运行良好。 不确定在其他平台上是如何工作的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM