29

我正在使用以下 C 代码从用户那里获取输入,直到 EOF 发生,但问题是这段代码不起作用,它在第一次输入后终止。谁能告诉我这段代码有什么问题。提前致谢。

float input;

printf("Input No: ");
scanf("%f", &input);

while(!EOF)
{
    printf("Output: %f", input);
    printf("Input No: ");
    scanf("%f", &input);
}
4

6 回答 6

49

EOF只是一个带有值的宏(通常是-1)。您必须针对 测试某些EOF内容,例如getchar()调用的结果。

测试流结束的一种方法是使用feof函数。

if (feof(stdin))

请注意,“流结束”状态只会在读取失败后设置。

在您的示例中,您可能应该检查 scanf 的返回值,如果这表明没有读取任何字段,则检查文件结尾。

于 2009-09-15T18:33:49.710 回答
9

EOF是 C 中的常量。您没有检查 EOF 的实际文件。你需要做这样的事情

while(!feof(stdin))

这是feof的文档。您还可以检查scanf的返回值。它返回成功转换的项目数,或者EOF是否到达文件末尾。

于 2009-09-15T18:34:06.713 回答
4

另一个问题是你scanf("%f", &input);只用阅读。如果用户输入了一些不能被解释为 C 浮点数的东西,比如“pi”,那么scanf()调用不会给 分配任何东西input,也不会从那里继续进行。这意味着它将尝试继续读取“pi”并失败。

考虑到while(!feof(stdin))其他海报正确推荐的更改,如果您在其中键入“pi”,则会出现一个无限循环,即打印出以前的值input并打印提示,但程序永远不会处理任何新输入。

scanf()返回它对输入变量的赋值数。如果它没有赋值,这意味着它没有找到一个浮点数,你应该阅读更多的输入,比如char string[100];scanf("%99s", string);. 这将从输入流中删除下一个字符串(最多 99 个字符,无论如何 - 额外char的是字符串上的空终止符)。

你知道,这让我想起了我讨厌的所有原因scanf(),以及为什么我使用fgets()它,然后可能使用sscanf().

于 2009-09-15T19:21:21.550 回答
-1

作为起点,您可以尝试更换

while(!EOF)

while(!feof(stdin))
于 2009-09-15T18:36:45.087 回答
-1

您想检查 scanf() 的结果以确保转换成功;如果没有,那么以下三件事之一是正确的:

  1. scanf() 阻塞了对 %f 转换说明符无效的字符(即,不是数字、点、'e' 或 'E' 的字符);
  2. scanf() 已检测到 EOF;
  3. scanf() 在读取标准输入时检测到错误。

例子:

int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
 * Loop while moreData is true
 */
while (moreData)
{
  errno = 0;
  int itemsRead = scanf("%f", &input);
  if (itemsRead == 1)
  {
    printf("Output: %f\n", input);
    printf("Input no: ");
    fflush(stdout);
  }
  else
  {
    if (feof(stdin))
    {
      printf("Hit EOF on stdin; exiting\n");
      moreData = 0;
    }
    else if (ferror(stdin))
    {
      /**
       * I *think* scanf() sets errno; if not, replace
       * the line below with a regular printf() and
       * a generic "read error" message.
       */
      perror("error during read");
      moreData = 0;
    }
    else
    {
      printf("Bad character stuck in input stream; clearing to end of line\n");
      while (getchar() != '\n')
        ; /* empty loop */
      printf("Input no: ");
      fflush(stdout);
    }
 }
于 2009-09-15T19:31:34.663 回答
-1
while(scanf("%d %d",a,b)!=EOF)
{

//do .....
}
于 2015-08-01T07:34:35.150 回答