我正在使用以下的 C 代码从用户处获取输入,直到出现 EOF,但问题是这个代码没有运行,它在获取第一个输入后就终止了。这个代码有什么问题?
float input;
printf("Input No: ");
scanf("%f", &input);
while(!EOF)
{
printf("Output: %f", input);
printf("Input No: ");
scanf("%f", &input);
}
我正在使用以下的 C 代码从用户处获取输入,直到出现 EOF,但问题是这个代码没有运行,它在获取第一个输入后就终止了。这个代码有什么问题?
float input;
printf("Input No: ");
scanf("%f", &input);
while(!EOF)
{
printf("Output: %f", input);
printf("Input No: ");
scanf("%f", &input);
}
EOF
只是一个带有值的宏(通常为-1)。您需要对某些内容进行测试,例如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 .....
}