Anonymous
Anonymous

Reputation: 13

Validating input using scanf (check whether input is char or int)

I want input entered by the user should be between 0 and 100. And if he or she enters a negative number or a number greater than 100 or a character, the loop must be triggered. I am using a do-while loop to validate the input entered by the user. But if I enter a character, the do while loop is executed infinite times. Can anyone explain why is this happening! and how to check if user has has entered a char or an int?

CODE IS WRITTEN IN C. AND COMPILED USING GCC.

int num;
do
{
    printf("num :");
    scanf("%d", &num);
}
while(num<0 ||  num>=100);

Upvotes: 1

Views: 4073

Answers (1)

Alex D&#237;az
Alex D&#237;az

Reputation: 2363

scanf() is expecting a number if it finds invalid input(something that doesn't match the format provided) it will return leaving the input buffer as is, that means leaving this invalid input there, then the loop condition evaluates to true and scanf() tries to read a number again to find the same invalid input as before, this repeats forever.

cleaning the input buffer will fix this, you can clean it like this:

#include <stdio.h>

void cleanBuffer(){
    int n;
    while((n = getchar()) != EOF && n != '\n' );
}
int main(int argc, char *argv[]) 
{
    int num = -1;
    do
    {
        printf("num :");
        scanf("%d", &num);
        cleanBuffer(); //we clean the buffer here
    }
    while(num<0 ||  num>=100);
    return 0;
}

Upvotes: 4

Related Questions