我正在使用以下 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 的返回值,如果这表明没有读取任何字段,则检查文件结尾。
另一个问题是你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()
.
作为起点,您可以尝试更换
while(!EOF)
和
while(!feof(stdin))
您想检查 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 .....
}