简体   繁体   English

检查用户输入的值

[英]checking value entered by user

With this code I am trying to check whether the value of I given correctly by the user or not. 使用此代码,我试图检查用户是否正确指定了I的值。 When I give integer value the program work perfectly and "done " gets printed on the screen but when i give a character such as "a" then it goes into an infinite loop and do not input the value again.... 当我给出整数值时,程序可以完美运行,并且"done "被打印在屏幕上,但是当我给出诸如"a"的字符时,它将进入无限循环,不再输入该值。

#include<stdio.h>
#include<stdlib.h>
int main()
{   
    int i;
    printf("Enter an integer: ");
    while(!scanf("%d",&i))
    {
        printf("no ");
    }
   printf("done\n");
   return 0;
}

OUTPUT 1: 输出1:

Enter an integer: 5
done

OUTPUT 2: 输出2:

Enter an integet: a
no no no no no no no no no no no no....upto infinite times

What couldn't be consumed is left on the stream, so you have to consume it before trying to read again. 无法使用的内容留在流中,因此您必须先使用它才能尝试再次读取。

#include<stdio.h>
#include<stdlib.h>
int main(void)
{   
    int i;
    printf("Enter an integer: ");
    while(!scanf("%d",&i))
    {
        scanf("%*s"); /* add this line to consume the garbage on the stream */
        printf("no ");
    }
   printf("done\n");
   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM