If you are going to take any input, it always works the same way. You job is to require the user to provide a valid input and handle all cases where the input is not valid. You have two options: (1) read each line of input at a time with fgets()
and then extract the value from the buffer filled with sscanf()
(or strtol()
), or (2) read the input value with scanf()
directly and manually empty stdin
after each input to remove any extraneous characters. Both are ultimately equivalent in what they do.
Whether reading the input with fgets()
or scanf()
, you must check whether the user generated a manual EOF
by pressing Ctrl + d (or Ctrl + z on windows).
If you use scanf()
or sscanf()
, you must validate (1) that a valid integer value was provided and (2) it is within the range of a 22-bit signed value.
The way you require the user to enter the input you need is you Loop Continually until the user provides valid input. After the input satisfies all of your criteria, then, and only then, do you exit the input loop.
Putting it altogether, you could do something similar to:
#include <stdio.h>
#define MAXSIGNED22 0x1FFFFF /* if you need a constant, #define one (or more) */
#define MINSIGNED22 -(MAXSIGNED22) - 1
int main (void) {
int value = 0; /* value to hold input */
for (;;) { /* loop continually until good input or manual EOF */
int rtn; /* return for scanf() */
fputs ("enter a 22-but signed number: ", stdout); /* prompt for input */
rtn = scanf ("%d", &value); /* read with scanf(), save return */
if (rtn == EOF) { /* check for manual EOF */
puts ("(user canceled input)\n");
return 0;
}
/* empty any extraneous characters from stdin */
for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
/* check matching failure */
if (rtn == 0)
fputs (" error: invalid integer value.\n", stderr);
/* validate in range of 22-bit */
else if (value < MINSIGNED22 || MAXSIGNED22 < value)
fputs (" error: value out of range for 22-bit.\n", stderr);
/* good 22-bit value, break loop */
else
break;
}
printf ("\nvalid 22-bit signed number: %d\n", value);
}
Assuming a twos-compliment representation of negative numbers, the valid range of a signed 22-bit number is -2097152
-> 2097151
. See min and max value of data type in C
Example Use/Output
$ ./bin/22bit
enter a 22-but signed number: 12345678
error: value out of range for 22-bit.
enter a 22-but signed number: -12345678 (and other junk)
error: value out of range for 22-bit.
enter a 22-but signed number: bananas!
error: invalid integer value.
enter a 22-but signed number: 2097152
error: value out of range for 22-bit.
enter a 22-but signed number: 2097151
valid 22-bit signed number: 2097151
and
$ ./bin/22bit
enter a 22-but signed number: -2097153
error: value out of range for 22-bit.
enter a 22-but signed number: -2097152
valid 22-bit signed number: -2097152
Look things over and let me know if you have any questions.