- num = 0;
- for (sp = buf; (c=getchar()) != '\n'; *sp++ = c)
- if (c == -1) /* check for interrupted system call */
- goto inter;
- *sp = c;
- if (sp == buf)
- continue;
- for (sp = buf; isspace((unsigned char)*sp); sp++)
- continue;
- for (; isdigit((unsigned char)*sp); sp++)
- num = num * 10 + *sp - '0';
- if (*sp == '\n')
- return num;
- else
+ fgets(buf, sizeof(buf), stdin);
+ if (feof(stdin))
+ return 0;
+ sp = strchr(buf, '\n');
+ if (sp)
+ *sp = '\0';
+ errno = 0;
+ num = strtol(buf, &sp, 10);
+ if (errno || strlen(sp) > 0 || num < 0 || num >= INT_MAX) {