当我给scanf()一个非数字作为输入时,如何继续循环?
我想出了一个简单的例子。在这里,它将从用户处获取整数值并显示该值。 当我输入一个字符而不是一个整数时,我想跳过这个过程,然后再试一次 请用户输入。 为此,我编写了下面的代码,但当我输入字符时,它将继续循环,但在继续时,它不会向用户请求输入。请给出一个解决方案当我给scanf()一个非数字作为输入时,如何继续循环?,c,scanf,C,Scanf,我想出了一个简单的例子。在这里,它将从用户处获取整数值并显示该值。 当我输入一个字符而不是一个整数时,我想跳过这个过程,然后再试一次 请用户输入。 为此,我编写了下面的代码,但当我输入字符时,它将继续循环,但在继续时,它不会向用户请求输入。请给出一个解决方案 #include <stdio.h> int main() { int n; while(1){ if(scanf("%d",&n)==0){
#include <stdio.h>
int main()
{
int n;
while(1){
if(scanf("%d",&n)==0){
printf("Error:Checkyour input\n");
continue;
}
printf("the input =%d\n",n);
}
}
发生这种情况的原因是,ENTER键[a\n]存储在输入缓冲区中,并持续向[next]scanf提供错误的输入 对代码进行以下更改
#include<stdio.h>
int main() //add the return type.
{
int n;
while(1){
if(scanf(" %d",&n)==0){
while (getchar() !='\n'); //eat up all the _invalid_ input present in input buffer till newline
printf("Error:Check your input\n");
continue;
}
printf("the input =%d\n",n);
}
return 0; //add the return value.
}
当scanf无法转换某些内容(例如,您键入的是字母a而不是数字)时,它会将无法读取的字符留在输入中,由另一个I/O调用处理。如果这是同样的扫描,它将再次失败,令人恶心。如果您的代码在标准输入上获得EOF,那么它也会出现错误行为
您有多种选项可以修复它:
当scanf不返回1时,您可以中断循环,在第一个错误或EOF时停止。
您可以使用getchar至少读取停止输入的字符,可以选择读取到下一个换行符或EOF。
您可以使用不同的scanf格式来读取垃圾:例如,scanf%*[-+0-9]可以跳过不是整数一部分的所有字符。但是,请注意,这可能会在输入中留下,因此并不安全。也许scanf%*[^\n]会更好。*抑制赋值,因此它不需要放置读取的数据。
继续;->scanf%*[^\n];持续请注意,如果用户在典型的Unix机器上指示EOF键入control-D,则会有一个无限循环,因为scanf不会返回0。此外,如果用户在键入字母或标点符号后指示EOF,则会得到不同的无限循环,因为getchar不返回换行符。总是考虑EOF too。对。我会相应地更新我的答案。谢谢:-。我诊断的两个无限循环中有一个是固定的。当retval=scanf%d,&n!=EOF作为外循环条件,我尽可能避免无限循环。
#include<stdio.h>
int main() //add the return type.
{
int n;
while(1){
if(scanf(" %d",&n)==0){
while (getchar() !='\n'); //eat up all the _invalid_ input present in input buffer till newline
printf("Error:Check your input\n");
continue;
}
printf("the input =%d\n",n);
}
return 0; //add the return value.
}
#include<stdio.h>
int main()
{
int n;
int retval = 0;
while(1){
retval = scanf(" %d",&n);
if (retval ==1)
printf("the input =%d\n",n);
else if (retval == 0)
{
while (getchar() !='\n');
printf("Error:Check your input\n");
continue;
}
else //includes EOF case
break;
}
return 0;
}