在C中检测EOF

我使用以下C代码从用户获取输入,直到EOF发生,但问题是此代码不起作用,它在第一次输入后终止。 任何人都可以告诉我这个代码有什么问题。 提前致谢。

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

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

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

 if (feof(stdin)) 

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

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

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

 while(!feof(stdin)) 

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

另一个问题是你正在使用scanf("%f", &input); 只要。 如果用户键入的内容不能被解释为C浮点数,例如“pi”,则scanf()调用将不会为input分配任何内容,也不会从那里进行任何操作。 这意味着它将尝试继续阅读“pi”,并且失败。

鉴于其他海报正确推荐的while(!feof(stdin))的变化,如果你输入“pi”,就会有无限循环打印输出的前值并打印提示,但程序永远不会处理任何新的输入。

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

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

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

 while(!EOF) 

 while(!feof(stdin)) 

您想检查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); } } 
 while(scanf("%d %d",a,b)!=EOF) { //do ..... }