C - Check that an int read by scanf is in the rang

2019-08-05 05:42发布

问题:

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().

回答1:

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()

num = INT_MAX;
i = 0;

while(num != 0){
    str[i] = num % 10;
    num = num / 10;
    i++;
}

The number would be opposite in this string you can get it reversed quite easily by a simple loop

Then use strcmp();



回答2:

Use s conversion specifier with scanf to read the string and use strtol 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 a long integer
  • Then check the long number is between INT_MIN and INT_MAX.


回答3:

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:

int foo = /* some value to test */;
long bar = (long)foo;

if ( (bar < (long)INT_MIN) || (bar > (long)INT_MAX) ) return false;


标签: c int range