This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
sys_prog/myscanf.c
2019-10-03 16:34:06 +02:00

50 lines
750 B
C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <limits.h>
char next_sign_char();
inline char next_sign_char() {
char c;
while (isspace(c = getchar()));
return c;
}
int read_int(int* p) {
int i = 0;
bool pos = true;
char c = next_sign_char();
if (c == '-' || c == '+') {
pos = c == '+';
} else if (!isdigit(c)) {
return 0;
} else {
i = c - '0';
}
while ((c = getchar()) != EOF && c != '\n' && c != ' ') {
if (!isdigit(c)) return 0;
int digit = c - '0';
if ((pos && i > (MAX_INT - digit) / 10) ||
(!pos && i > (-1 * MIN_INT - digit) / 10)) {
break;
}
i *= 10;
i += c - '0';
}
*p = pos ? i : -i;
return 1;
}
int main() {
int a;
read_int(&a);
printf("%d", a);
}