Question

I need to make a function that gets input from the user and makes sure that it is a whole number and does not contain any character.

I wrote this code which works perfectly for integers and for single characters. But it terminates if I enter dfd i.e. multiple character input. Below is my code compiled with gcc on Linux:

#include <ctype.h>

int getint()
{
    int input = 0;
    int a;
    int b, i = 0;
    while((a = getchar()) != '\n')
    {
        if (a<'0'||a>'9')
        {
            printf("\nError in input!Please try entering a whole number again:");
            input=0;
            fflush(stdin);
            return getint();
        }
        b = a - '0';
        input = ((input*10) + b);
        i++;
    }
    return input;
}
Was it helpful?

Solution 2

The problem may be that calling fflush(stdin) is undefined. fflush is for flushing an output stream, not an input stream. Try replacing it with another way to clear the remaining input buffer, like while (getchar() != '\n'); and see if that resolves the issue. (you should probably do something more robust like also catching EOF so you're not in an infinite loop)

OTHER TIPS

Calling fflush on an input stream invokes undefined behaviour. Even if your implementation defines it for input streams, it's not portable. There is no standard way to flush an input stream. Therefore, the fflush(stdin); is not correct. You should read the characters and discard them till and including the newline in the stdin buffer. I suggest the following change to your function.

int getint(void) {
    int input = 0;
    int a;

    while((a = getchar()) != '\n') {
        if (a < '0' || a > '9') {
            printf("Error in input!Please try entering a whole number again:\n");
            input = 0;

            // read and discard characters in the stdin buffer up till
            // and including the newline
            while((a = getchar()) != '\n'); // the null statement
            return getint();  // recursive call
        }
        input = (input * 10) + (a - '0');
    }
    return input;
}

Also, please read this C FAQ - If fflush won't work, what can I use to flush input?

Changing the fflush to fpurge caused your program to start working for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top