#include <stdio.h>
#include <ctype.h>

int mygeti(int *result)
{
        char c, buff [ 13 ]; /* signed 32-bit value, extra room for '\n' and '\0' */
        return fgets(buff, sizeof buff, stdin) && !isspace(*buff) &&
        sscanf(buff, "%d%c", result, &c) == 2 && (c == '\n' || c == '\0');
}

int main(void)
{
        int value;
        do {
                fputs("Enter an integer: ", stdout);
                fflush(stdout);
        } while ( !mygeti(&value) );
        printf("value = %d\n", value);
        return 0;
}

/* my output
Enter an integer: one
Enter an integer:
Enter an integer: f123
Enter an integer: 123f
Enter an integer:  123
Enter an integer: 123
Enter an integer: 1.23
Enter an integer: -42
value = -42
*/

/* note: this line in the above has a space character following the 123
Enter an integer: 123
*/
2
Contributors
1
Reply
6
Views
12 Years
Discussion Span
Last Post by drxs33
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.