Search code examples
cscanfinfinite-loopturbo-c

scanf is not waiting for an integer input


printf("Enter an integer: ");
status = scanf("%d", &integer);

if (status == 0){
    do{
        printf("Please enter an integer: ");
        status = scanf("%d", &integer);
    }
    while (status == 0);
}

I'm trying to prevent a user from entering a data of type of character. However, after the prompt, "Please enter an integer: ", it doesn't wait for an input. Hence, it goes into an infinite loop whenever I enter a letter at the first prompt. How do I fix this? Any heeelp will be greatly appreciated!


Solution

  • You need clean the buffer first, you can use fflush(stdin); like this:

    int integer, status=0;
    if (status == 0)
    {
        do
        {
            printf("\nPlease enter an integer: ");
            status = scanf("%d", &integer);
            fflush(stdin);
        }
        while (status == 0);
    }
    

    It's not in standard C using fflush(stdin) but you can clean the buffer in other ways.

    You can build your own function to clean the buffer, like this:

    void flushKeyBoard()
    {
        int ch; //variable to read data into
        while((ch = getc(stdin)) != EOF && ch != '\n');
    }
    

    To clean the screen call this function:

    void clrscr()
    {
        system("@cls||clear");
    }
    

    Final code:

    #include <stdio.h>
    
    void clrscr()
    {
        system("@cls||clear");
    }
    void flushKeyBoard()
    {
        int ch; //variable to read data into
        while((ch = getc(stdin)) != EOF && ch != '\n');
    }
    int main()
    {
        int integer, status=0;
        if (status == 0)
        {
            do
            {
                printf("\nPlease enter an integer: ");
                status = scanf("%d", &integer);
                flushKeyBoard();
                clrscr();
            }
            while (status==0);
        }
    }