/* * Program to get integer, with check for overflow. */ #include #include #include #include bool get_int(int * n); int main(void) { printf("enter integer:\n"); int input; if (get_int(&input)) { printf("you entered %d\n", input); } else { printf("error\n"); } } /* * function to read int from standard input * skips leading whitespace * returns true if value up to next whitespace can be converted to "int", * false otherwise */ bool get_int(int * n) { int inchar; /* skip leading whitespace */ do { inchar = getchar(); } while (isspace(inchar)); /* at this point, inchar is first non-whitespace */ /* look for "-" at start */ int sign = 1; if (inchar == '-') { sign = -1; inchar = getchar(); } /* at this point, inchar should be start of number */ if (!isdigit(inchar)) { return false; } /* read in digits up to non-digit and accumulate result */ /* (have first digit) */ int temp = 0; do { int digit = inchar - '0'; /* want to check temp * 10 + digit > INT_MAX */ /* but evaluating that could overflow */ /* test something algebraically equivalent that won't overflow */ if (temp > (INT_MAX - digit) / 10) { return false; } temp = temp * 10 + digit; inchar = getchar(); } while (isdigit(inchar)); /* at this point, inchar is the first non-digit */ /* check for ending whitespace */ if (!isspace(inchar)) { return false; } /* store result for caller */ *n = sign * temp; return true; }