简体   繁体   中英

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. 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....

#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:

Enter an integer: 5
done

OUTPUT 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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