I have got this code that reads an integer using scanf and checks if it is actually an integer by looking at the buffer.
int e_1;
char c[1];
// noNeedToCleanBuffer is used to avoid buffer cleaning the first time.
int noNeedToCleanBuffer = 1;
do {
// Clears the buffer.
if (!noNeedToCleanBuffer)
while ((c[0] = getchar()) != '\n') ;
noNeedToCleanBuffer = 0;
printf("Input an integer value: \n");
e_1 = scanf("%d", &n);
c[0] = getchar();
} while ((e_1 != 1 && c[0] != 10) || (e_1 == 1 && c[0] != 10));
However I cannot figure out how to check if the input is between INT_MIN and INT_MAX (I get these from limits.h).
I was thinking of getting the number as a string and compare it with two strings that would represent INT_MIN and INT_MAX, but since I am using the standard c99 I am not allowed to use atoi() or itoa().
Use
s
conversion specifier withscanf
to read the string and usestrtol
function to check the number.strtol
let you first check if number is in the correct format (an integer) and if it is representable as along
integerlong
number is betweenINT_MIN
andINT_MAX
.The value of a variable that is of any given data type (including
int
) will always be within the range of that data type. This is defined and enforced by the platform for which the application is compiled.If you just want to go through an exercise of "proving" that the variable is within the bounds of your type, you have to cast it to a variable of such a type that can accommodate a greater range of values. For example:
If you really just want to check store it-
1.)Store in long and then check
2.)Store the number in string then convert the INT_MAX into a string by getting each digit and storing in string and then using strcmp()
The number would be opposite in this string you can get it reversed quite easily by a simple loop
Then use strcmp();