问题在于
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
while(a != '\n')
scanf("%c",&a);
}
是如果a
恰好包含'\n'
扫描之前,扫描失败,内部while
循环根本不运行。所以
如果扫描尝试解析失败int
来自输入流,因为输入是例如"ab c\n"
,有问题的输入保留在输入流中,下一个scanf
在外while
循环控制无法解析int
again, a
遗迹'\n'
, 重复。
如果在从流中读取字符之前发生输入错误a
, the scanf
在外循环中,由于流损坏,控制失败,重复。
在另一个版本中,
while(scanf("%d%c",&num,&a) != 2 || a != '\n')
{
printf("Please enter an integer only : ");
if(a == '\n')
scanf("%c",&a);
else
{
while(a != '\n')
scanf("%c",&a);
}
}
只要有输入要从流中读取,您至少会取得一些进展,因为无论什么a
包含,在尝试下一次解析之前,您至少从输入流中读取一个字符int
。如果输入流损坏/关闭/过早结束,也会导致无限循环,例如如果您从空文件重定向标准输入。您可以让该循环也输出多个"Please enter an integer only : "
通过提供诸如“a\nb\nc\nd\n”之类的输入来发送消息。
所以你应该检查是否scanf
在从输入转换任何内容之前遇到流的结尾或其他一些读取错误,并在这种情况下中止:
int reads;
while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != '\n')
{
printf("Please enter an integer only : ");
// read at least one character until the next newline
do {
reads = scanf("%c", &a);
}while(reads != EOF && a != '\n');
}