Reputation: 65
I got this code:
char a[151];
scanf ("%150s", a);
In a
could be a number and if so, I need to determine, if a < INT_MAX
. I don't know, how to do that, because in each index of a
char could be a number, it means 150-digit number which could cause overflow if I store a value into some int or anything else. Any suggestions?
Upvotes: 2
Views: 123
Reputation: 153640
Call strtol()
and test errno
.
If the correct value is outside the range of representable values,
LONG_MIN
,LONG_MAX
, ... the value of the macroERANGE
is stored inerrno
. C11dr §7.22.1.4 8
char a[151];
scanf ("%150s", a);
char *endptr;
errno = 0;
long num = strtol(a, &endptr, 10);
if (errno == ERANGE) Overflow(); // outside `long` range
if (num > INT_MAX) Overflow(); // greater than `INT_MAX`
Upvotes: 2
Reputation: 510
One way to solve:
1. INT_MAX = 2147483647 --> contains 10 digits
2. len = strlen(a);
3. if (len > 10)
a. true --> then a > INT_MAX --> print answer and return
b. false, go to step 4
4. if (len < 10)
a. true --> then a < INT_MAX --> print answer and return
b. false, go to step 5
5. (len == 10) case
6. if (a[9]-'0' > 2) // 10th digit is > 2
a. true --> then a > INT_MAX --> print answer and return
b. false, go to step 7
7. int num = atoi(a);
9. Compare num and INT_MAX and print answer and return
[NOTE: Negative numbers not considered here]
Upvotes: 0